How can I deserialize xml with the default namespace?

I am trying to deserialize an Atom XML file created by one of the internal systems. However, when I try:

public static MyType FromXml(string xml) { XmlSerializer serializer = new XmlSerializer(typeof(MyType )); return (MyType) serializer.Deserialize(new StringReader(xml)); } 

it throws an exception in the namespace definition:

 System.InvalidOperationException: <feed xmlns='http://www.w3.org/2005/Atom'> was not expected. 

When I add a namespace to the XmlSerializer constructor, my object is completely empty:

  public static MyType FromXml(string xml) { XmlSerializer serializer = new XmlSerializer(typeof(MyType ), "http://www.w3.org/2005/Atom"); return (MyType) serializer.Deserialize(new StringReader(xml)); //this will return an empty object } 

Any ideas how I can make it work?

+6
c # xml serialization
source share
2 answers

It's hard to research this without being able to look at how your object model is related to xml (i.e., each sample); however, you should be able to do something like:

 [XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")] public class MyType {...} 

As an example with a limited atom (which works fine with some atom of the sample, I have a β€œhand”):

 class Program { static void Main() { string xml = File.ReadAllText("feed.xml"); XmlSerializer serializer = new XmlSerializer(typeof(MyType)); var obj = (MyType)serializer.Deserialize(new StringReader(xml)); } } [XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")] public class MyType { [XmlElement("id")] public string Id { get; set; } [XmlElement("updated")] public DateTime Updated { get; set; } [XmlElement("title")] public string Title { get; set; } } 
+10
source share

You can debug XML serialization by adding it to app.config

 <system.diagnostics> <switches> <add name="XmlSerialization.Compilation" value="1" /> </switches> </system.diagnostics> 

C # files for the serializer are created in your temporary folder, and you can open them in VS for debugging.

Also see the XmlNamespaceManager (even for default namespaces).

+5
source share

All Articles