Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

c# - Use multiple namespaces when deserializing with .NET XmlSerializer

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">

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; }
}

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.

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?)

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[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; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...