Use multiple namespaces when deserializing with .NET XmlSerializer(使用 .NET XmlSerializer 反序列化时使用多个命名空间)
问题描述
我正在尝试使用两个命名空间来反序列化 XML,就像这样
I'm trying to deserialize XML with two namespaces, like this
<records xmlns="http://www.foo.com/xml/records/1.1">
<record xmlns="http://www.foo.com/xml/record/1.1">
有时是旧版本
<records xmlns="http://www.foo.com/xml/records/1.1">
<record xmlns="http://www.foo.com/xml/record/1.0">
我的 Records.cs 类有
My Records.cs class has
[XmlRoot(ElementName = "records", Namespace = "http://www.foo.com/xml/records/1.1")]
public class Records
{
[System.Xml.Serialization.XmlElementAttribute("record")]
public List<Record> Records { get; set; }
}
我希望记录列表能够包含 1.0 版或 1.1 版记录
I want the Records list to be able to contain either a version 1.0 or version 1.1 Record
/// <remarks/>
[XmlRoot(IsNullable = false, ElementName = "record", Namespace = "http://www.foo.com/xml/record/1.0")]
public partial class Record
{
/// <remarks/>
public Record()
{
}
}
/// <remarks/>
[XmlRoot(IsNullable = false, ElementName = "record", Namespace = "http://www.foo.com/xml/record/1.1")]
public partial class Record11 : Record
{
/// <remarks/>
public Record11()
{
}
}
所以我假设子类化记录会起作用.
so I assumed subclassing the record would work.
反序列化时出现反射异常,异常指向 XmlChoiceIdentifier 属性.但是,这似乎与枚举有关.
I get a Reflection exception when deserializing and the exception points me to the XmlChoiceIdentifier attribute. However, that seems related to enums.
任何人都知道如何做我想做的事(支持反序列化同一架构的多个版本?)
Anyone know how to do what I want to do (support deserializing multiple versions of the same schema?)
谢谢.
推荐答案
[XmlRoot]
在您的示例中的 Record
和 Record11
属性将被忽略.只有当元素是树中的根时,它们才有意义.你需要做的是:
[XmlRoot]
attributes on both Record
and Record11
in your example will be ignored. They only have meaning when element is a root in the tree. What you rather need to do is this:
[XmlRoot(ElementName = "records",
Namespace = "http://www.foo.com/xml/records/1.1")]
public class Records
{
[XmlElement(Type = typeof(Record),
ElementName = "record",
Namespace = "http://www.foo.com/xml/records/1.0")]
[XmlElement(Type = typeof(Record11),
ElementName = "record",
Namespace = "http://www.foo.com/xml/records/1.1")]
public List<Record> Records { get; set; }
}
这篇关于使用 .NET XmlSerializer 反序列化时使用多个命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 .NET XmlSerializer 反序列化时使用多个命名空间
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01