I'm trying to do what seems like a simple task, but it's proving to be quite complicated.
.NET's System.Xml.Serialization
namespace seems to do a really good job of supporting static XML structure, but not so much dynamic structure.
I'm trying to set up an XML document with elements whose children could have one of many types and in arbitrary order. It is my understanding that you can name lists of child elements with the same name this way:
[Serializable]
[XmlRoot("Parent")]
public class MyElement
{
[XmlElement("Child")]
public string[] MyChildren { get; set; }
}
This will result in XML that looks like this:
<Parent>
<Child></Child>
...
<Child></Child>
</Parent>
I'm trying to have a structure that looks like this:
<Parent>
<ChildTypeA></ChildTypeA>
<ChildTypeB></ChildTypeB>
...
<ChildTypeZ></ChildTypeZ>
</Parent>
where there is no particular order to them, and types can appear more than once. I've seen some answers where people suggest to use the XmlType
attribute on classes to declare the element name, but it seems that the functionality changed between then and now, because all that type does is declare the schema type of the element:
[Serializable]
[XmlRoot("Parent")]
public class MyElement
{
[XmlElement]
public BaseChildElement[] MyChildren { get; set; }
}
[Serializable]
public abstract class BaseChildElement {}
[Serializable]
[XmlType("ChildTypeA")]
public class ChildElementA : BaseChildElement
{
[XmlAttribute]
public string Content { get; set; }
}
[Serializable]
[XmlType("ChildTypeB")]
public class ChildElementB : BaseChildElement
{
[XmlAttribute]
public string Content { get; set; }
}
This will produce XML that looks like this:
<Parent>
<MyChildren xsi:type="ChildTypeA" Content="" />
<MyChildren xsi:type="ChildTypeB" Content="" />
<MyChildren xsi:type="ChildTypeA" Content="" />
...
</Parent>
Does someone know how to produce a dynamic list of child elements where the class of the child element gets to set the element name?
HTML is a perfect example of what I'm trying to do. In HTML you can have child elements of arbitrary types in arbitrary order:
<html>
<head></head>
<body>
<p>
<a href="google.com">Google</a>
<span>Some text</span>
<p>
<div>
<button>Click me</button>
<a href="stackoverflow.com">Stack Overflow</a>
<div>
<p>Hello world</p>
</body>
</html>