使用.NET XmlSerializer的反序列化时,使用多个命名空间 [英] Use multiple namespaces when deserializing with .NET XmlSerializer

查看:706
本文介绍了使用.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">



有时旧版本的

and sometimes an older version

<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] 属性上都录制 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的反序列化时,使用多个命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆