简体   繁体   English

XmlSerializer.Deserialize - 忽略不必要的元素?

[英]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. 我有一个XSD架构,我已经生成了一个使用xsd.exe的类,我正在尝试使用XmlSerializer.Deserialize从XML文件创建该类的实例,该文件应该符合XSD架构。 Unfortunately the XML file has some extra elements that the schema is not expecting, which causes a System.InvalidOperationException to be thrown from Deserialize . 遗憾的是,XML文件有一些架构不期望的额外元素,这会导致从Deserialize抛出System.InvalidOperationException

I've tried adding <xs:any> elements to my schema but this doesn't seem to make any difference. 我已经尝试将<xs:any>元素添加到我的模式中,但这似乎没有任何区别。

My question is: is there any way to get XmlSerializer.Deserialize to ignore these extra elements? 我的问题是:有没有办法让XmlSerializer.Deserialize忽略这些额外的元素?

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. 为了公平归属,我在阅读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. 您必须修复架构或手动修改xsd.exe生成的代码以允许反序列化XML。 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. 您还可以尝试在Visual Studio或任何其他具有架构支持的XML编辑器中打开XML文档+架构,以修复架构或XML文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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