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

发布于 2024-09-12 23:32:34 字数 353 浏览 7 评论 0原文

我有一个 XSD 架构,我已经生成了一个使用 xsd.exe 的类,并且我正在尝试使用 XmlSerializer.Deserialize 从 XML 文件创建该类的实例,该文件是应该符合 XSD 架构。不幸的是,XML 文件包含一些模式不期望的额外元素,这会导致从 Deserialize 抛出 System.InvalidOperationException

我尝试将 元素添加到我的架构中,但这似乎没有任何区别。

我的问题是:有没有办法让 XmlSerializer.Deserialize 忽略这些额外的元素?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的位置 2024-09-19 23:32:34

我通常向所有实体类添加额外的属性或字段,以获取额外的元素和属性,类似于下面的代码:

[XmlAnyAttribute]
public XmlAttribute[] AnyAttributes;

[XmlAnyElement]
public XmlElement[] AnyElements;

根据生成代码的复杂性,您可能不会发现在每个实体上手动插入此代码很有吸引力。也许唯一稍微不那么繁琐的就是在基类中定义这些属性并确保所有实体都继承该基类。

为了公平起见,我是在阅读 DasBlog 的源代码时第一次接触到这种模式的。

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.

傻比既视感 2024-09-19 23:32:34

我认为没有办法做到这一点。您必须修复架构或手动修改 xsd.exe 生成的代码以允许反序列化 XML。您还可以尝试在 Visual Studio 或任何其他具有架构支持的 XML 编辑器中打开 XML 文档 + 架构,以修复架构或 XML 文档。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文