3

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.

1 Answer 1

12

[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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a solution where sometimes xml root has namespace defined and other times it is skipped? [XmlRoot()] cannot be attributed multiple times same as [XmlElement()]... Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.