I have a class hierarchy with base class Element where each derived element type may have collection of child elements.
public abstract class Element
{
[XmlArray("children")]
[XmlArrayItem("leaf", typeof(Leaf))]
[XmlArrayItem("container", typeof(Container))]
public List<Element> Children { set; get; }
};
public enum FieldType
{
[XmlEnum(Name = "numeric")]
Numeric,
[XmlEnum(Name = "text")]
Text
};
[XmlType("container")]
public class Container : Element
{
};
[XmlType("leaf")]
public class Leaf : Element
{
[XmlAttribute(AttributeName = "type")]
public FieldType Type { set; get; }
};
Minimum tree serialized:
Container root = new Container();
root.Children = new List<Element>();
root.Children.Add(new Leaf() { Type = FieldType.Text });
var xmlserializer = new XmlSerializer(typeof(Container));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, root);
Console.WriteLine(stringWriter.ToString());
}
which produces:
<?xml version="1.0" encoding="utf-16"?>
<container>
<children>
<leaf type="text" />
</children>
</container>
That is all fine, unfortunately I need to get rid of the <children>
level. So I need to customize the serialization and write the elements and their attributes myself. So I use reflection to enumerate properties and write the values as string. However, the conversion for enum types needs to be redone as well.
In this example, having FieldType
value, can I have serialization to return string containing "text", without actually digging into XmlEnumAttribute?
When I serialize FieldType value, the best serializer can do is:
<?xml version="1.0" encoding="utf-16"?>
<ValueType>numeric</ValueType>
However, somewhere inside the serializer there is a mechanism that converts the enum value to "numeric" string. Is that part accessible as converter? Or I just need to create the converter that reads XmlEnumAttribute?
question from:
https://stackoverflow.com/questions/65902077/use-xmlserialzer-to-convert-object-property-into-attribute-value 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…