简体   繁体   中英

XmlSerializer.Deserialize - ignore unnecessary elements?

I've got an XSD schema which I've generated a class for using xsd.exe, and I'm trying to use XmlSerializer.Deserialize to create an instance of that class from an XML file that is supposed to conform to the XSD schema. Unfortunately the XML file has some extra elements that the schema is not expecting, which causes a System.InvalidOperationException to be thrown from Deserialize .

I've tried adding <xs:any> elements to my schema but this doesn't seem to make any difference.

My question is: is there any way to get XmlSerializer.Deserialize to ignore these extra elements?

I usually add extra properties or fields to all entity classes to pick up extra elements and attributes, looking something like the code below:

[XmlAnyAttribute]
public XmlAttribute[] AnyAttributes;

[XmlAnyElement]
public XmlElement[] AnyElements;

Depending on the complexity of your generated code, you may not find hand-inserting this code on every entity appealing. Perhaps only-slightly-less-tedious is defining these attributes in a base class and ensuring all entities inherit the base.

To give fair attribution, I was first introduced to this pattern when reading the source code for DasBlog.

I don't think there is an option to do this. You either have to fix the schema or manually modify the code generated by xsd.exe to allow the XML to be deserialized. You can also try to open the XML document + schema in Visual Studio or any other XML editor with schema support to either fix the schema or the XML document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM