views:

1418

answers:

2

I am trying to deserialize a Xml Fragment. I am nearly there but it throws an error where by it does not expect the first element. An example of the XML in the stream is as follows:

  <Project xmlns="http://schemas.datacontract.org/2004/07/Swissmod.Service.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;
  <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 am using 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 throws the following error:

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

Anyone have any ideas how I can read an XML Fragment using a XML Reader?

TIA

Andrew

+2  A: 

In your Project class definition, have you tried specifying a namespace in an XmlRoot attribute?

Jeremy
Lol, and thats that!! Thanks very much for your time. Adding that attribute sorted it a treat. Thank you. :-)
REA_ANDREW
A: 

Thank you for posting this code snippet actually. I was looking for a way of doing this, this afternoon. I was getting aresponse stream from a rest webservice, and I was just looking how to conform the response to an xsd. I stumbled across your post and I manage to implement my solution by using your code as a guideline. Awesome thank you, by you having a problem helped me avoid one !! :-)

Gary Woodfine
Brilliant! :-) I appreciate things like that too when it happens to me. I am glad it has helped you also. Cheers again :-)
REA_ANDREW