John Askew John Askew - 19 days ago 7
C# Question

C# Deserialize inner XML to string

I have the following XML:

<MyType>
<MyProperty1>Value 1</MyProperty1>
<MyProperty2>Value 2</MyProperty2>
<MyNestedXml>
<h1>Heading</h1>
<p>Lorum</p>
<p>Ipsum</p>
</MyNestedXml>
</MyType>


This can be deserialized to XML in C# by creating classes and adding attributes as below:

[Serializable]
public class MyType
{
[XmlElement("MyProperty1")
public string MyProperty1 { get; set; }

[XmlElement("MyProperty2")
public string MyProperty2 { get; set; }

[XmlIgnore]
public string MyNestedXml { get; set; }
}


However, the inner XML within the element varies and doesn't follow a consistent structure which I can effectively map using attributes.

I don't have control over the XML structure unfortunately.

I have tried using an [XmlElement("MyNestedXml") with an XmlNode type but this results in the first child node being deserialized instead of the entire inner XML.

I have also tried deserializing to a type of string but that throws an InvalidOperationException:

"Unexpected node type Element. ReadElementString method can only be called on elements with simple or empty content."

The problem is that the content of the MyNestedXml element could be an array of Elements sometimes but could be simple or empty content at other times.

Ideally I could use a different serialization attribute such as [XmlAsString] to skip serialization altogether and just assign the inner XML as is.

The intended result would be a class of type MyType having a property MyProperty1 = "
Value 1
", a property MyProperty2 = "
Value 2
", and a property MyNestedXml = "
<h1>Heading</h1><p>Lorum</p><p>Ipsum</p>
".

Answer

Make it an XmlElement property with the XmlAnyElement attribute and the serializer will deserialize an arbitrary XML structure.

[XmlRoot("MyType")]
public class MyType
{
    [XmlElement("MyProperty1")]
    public string MyProperty1 { get; set; }

    [XmlElement("MyProperty2")]
    public string MyProperty2 { get; set; }

    [XmlAnyElement("MyNestedXml")]
    public XmlElement MyNestedXml { get; set; }
}
Comments