Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 588
Ben Hymers Avatar asked May 08 '26 06:05

Ben Hymers


2 Answers

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.

like image 192
kbrimington Avatar answered May 10 '26 20:05

kbrimington


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.

like image 29
chris166 Avatar answered May 10 '26 20:05

chris166



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!