开发者

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开发者_如何学JAVA 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜