Problems with comments in XmlSerialzier

I am trying to load an XML file using this code:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject)); StreamReader reader = new StreamReader(fileName); object myobject = xmlSerializer.Deserialize(reader); 

When a file contains a comment like this:

 <?xml version="1.0" encoding="utf-8"?> <!-- edited with XMLSpy v2007 sp2 --> <route> <!--File created on 26-Nov-2010 12:36:42--> <file_content>1 <!--0 = type1 ; 1 = type2--> </file_content> </route> 

XmlSerializer returns an error like

Unexpected node type Comment. The ReadElementString method can be called only for elements with simple or empty content.

When I delete these comments in the file, it works fine.

I donโ€™t know where the problem is, any ideas?

+4
source share
3 answers

As you can see, comments are not allowed in serialized XML, but this should not be a problem for you. You cannot control the source XML, but you control the deserialization process, so just delete all comments before deserialization:

  XmlSerializer xmlSerializer = new XmlSerializer(typeof(myobject)); // load document XmlDocument doc = new XmlDocument(); doc.Load(filename); // remove all comments XmlNodeList l = doc.SelectNodes("//comment()"); foreach (XmlNode node in l) node.ParentNode.RemoveChild(node); // store to memory stream and rewind MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Seek(0, SeekOrigin.Begin); // deserialize using clean xml xmlSerializer.Deserialize(XmlReader.Create(ms)); 

If your objects are huge and you deserialize a huge number of them in a short amount of time, howler, we can explore some of Xpath's extracurricular fast readers.

+4
source

I agree with @mmix, you will have to delete the comments before trying to serialize it.

There may be another way to remove comments, it may be using XmlReader with XmlReaderSettings

  public static T DeSerialize<T>(string filePath) { var x = new XmlSerializer(typeof (T)); //Serilaize would fail if there are comments in the xml document var xmlReaderSettings = new XmlReaderSettings {IgnoreComments = true}; var xmlReader = XmlReader.Create(filePath, xmlReaderSettings); return (T)x.Deserialize(xmlReader); } 
+2
source

I find jacob aloysious most elegant answer for the problem. It also works when reading RSS feeds using the System.ServiceModel.SyndicationFeed.Load function. Example below:

 public SyndicationFeed GetFeed(String url) { var request = (HttpWebRequest)WebRequest.Create(url); using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { Debug.Assert(responseStream != null, "responseStream != null"); var xmlReaderSettings = new XmlReaderSettings { IgnoreComments = true }; using (XmlReader xmlReader = XmlReader.Create(responseStream, xmlReaderSettings)) { var feed = SyndicationFeed.Load(xmlReader); return feed; } } } 
0
source

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


All Articles