thirstyAndreas thirstyAndreas - 3 months ago 28
C# Question

Deserialize xml Elements with same Attributes

I am deserializing a xml file with an attribute and a xml text. The problem is that those elements have the same attributes. So I am always getting the error that I must not have two identical TypeNames in XmlType.

My xml:



<group_id xsi:type="xsd:int">1</group_id>
<name xsi:type="xsd:int">myNameView</name>


And my C#:



[XmlType(AnonymousType = true, Namespace = "http://www.w3.org/2001/XMLSchema", TypeName = "int")]
[XmlRoot(ElementName = "group_id")]
public class Group_id
{
[XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "http://www.w3.org/2001/XMLSchema", TypeName = "int")]
[XmlRoot(ElementName = "name")]
public class Name
{
[XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Type { get; set; }
[XmlText]
public string Text { get; set; }
}


The problem is the TypeName in XmlType Attribute. If I name only one element with a TypeName it is correctly deserialized.

Answer

XmlSerializer handles types for you, based on the xsi:type attribute. By trying to handle these yourself, you're causing it some grief.

If you declare your elements as object, then the serializer will use the type attributes to determine how to deserialize the values. Note as your example is just a fragment, I've assumed root element called root:

[XmlRoot("root")]
public class Root
{
    [XmlElement("group_id")]
    public object GroupId { get; set; }

    [XmlElement("name")]
    public object Name { get; set; }
}

Now when you deserialize your example, you'd actually get an exception (as myNameView isn't an integer). You can fix by either changing the type to xsd:string or changing the value to a valid integer.

In the event the XML was valid, you'd see that the types deserialized map directly to the type attributes. See this fiddle for a working demo.