Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubles wtih comments in XmlSerialzier

I try to load a XML file with this code:

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

When the 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. ReadElementString method can only be called on elements with simple or empty content

When I remove this comments in file it's work fine.

I don´t know where is the problem, any ideas?

like image 784
Dav Avatar asked Feb 07 '11 08:02

Dav


1 Answers

As you can see comments are not allowed in the serialized XML, but this should pose no problem for you. You might not control the source XML but you control the deserialization process, so simply remove all comments prior to 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 short span, howler, we can investigate some out-of-framework fast Xpath readers.

like image 118
mmix Avatar answered Sep 18 '22 17:09

mmix