XmlSerializer. Skip xml unknown node

后端 未结 3 1915
遇见更好的自我
遇见更好的自我 2020-12-19 06:51

I have a problem with deserialization of my xml files. Let\'s pretend that we have a xml file and a class that we are using for deserialization to.

For example:

相关标签:
3条回答
  • 2020-12-19 07:04

    I know this doesn't answer your question, but I think if you change directions it will solve your problem...

    Did you create an XSD to define the XML Schema? If not, I recommend starting there and then using xsd2code to create the serialization class.

    0 讨论(0)
  • 2020-12-19 07:06

    To add to Martijn's answer:

    You can also collect unknown items in an array which you can access later.

    http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlanyelementattribute.aspx

    Public Class XClass
        ' Apply the XmlAnyElementAttribute to a field returning an array 
        ' of XmlElement objects.
        <XmlAnyElement()> Public AllElements() As XmlElement
    End Class 'XClass
    
    0 讨论(0)
  • 2020-12-19 07:12

    By default the XmlSerializer ignores unknown nodes (so elements as well). Now when you use the Order property like you do, you are telling explicitly in which Order to serialize/deserialize.

    So when the XmlSerializer comes to your description element this becomes a unknown element because it expects the type element. The rest will also be threated as unknown elements because they do not map anymore to your specified order. For example when it comes to your type element which has index two in your XML, it expects it be the enabled element so this element becomes unknown as well.

    You can check this behaviour by handling the UnknownNode event of the XmlSerializer class. This event will be fired for every unknown node it encounters.

    How to proceed? If the ordering has no meaning don't use it. There are situations where it does make sense to use ordering. A classical example I've seen multiple times are (legacy) apps which treat XML documents as strings and read all the elements from top to bottom.

    Another option would be implementing the IXmlSerializer interface, which gives you better control on how your object is serialized and deserialized.

    0 讨论(0)
提交回复
热议问题