How to deserialize an Xml fragment using XML Reader

I am trying to deserialize an Xml fragment. I am almost there, but it throws an error when it does not expect the first element. An example of XML in a stream is as follows:

  <Project xmlns="http://schemas.datacontract.org/2004/07/Swissmod.Service.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ClientID>1</ClientID> 
  <Created>2009-03-16T20:34:57.022167+00:00</Created> 
  <ID>22</ID> 
  <LastModified>2009-03-11T20:34:57.022167+00:00</LastModified> 
  <ProjectDescription>Description here</ProjectDescription> 
  <ProjectTitle>Poject title</ProjectTitle> 
  <UserID>5</UserID> 
  <Version>1234567</Version> 
  </Project>

I use the following code to deserialize:

  XmlSerializer serializer = new XmlSerializer(typeof(Project));
  XmlReaderSettings settings = new XmlReaderSettings();
  settings.ValidationFlags = XmlSchemaValidationFlags.None;
  settings.ValidationType = ValidationType.None;
  settings.ConformanceLevel = ConformanceLevel.Auto;
  settings.IgnoreProcessingInstructions = true;
  settings.NameTable = new NameTable();
  settings.NameTable.Add("http://schemas.datacontract.org/2004/07/Swissmod.Service.Model");
  XmlReader reader = XmlReader.Create(wresp.GetResponseStream(),settings);
  Project p = (Project)serializer.Deserialize(reader);

But the above leads to the following error:

There is an error in XML document (1, 2).
"<Project xmlns='http://schemas.datacontract.org/2004/07/Swissmod.Service.Model'> was not expected."

Does anyone have any ideas how I can read an XML fragment using an XML reader?

+3
source share
1 answer

In the definition of the Project class, did you try to specify the namespace in the XmlRoot attribute?

+4
source

Source: https://habr.com/ru/post/1704862/


All Articles