[英]Use XmlSerialzer to convert object property into attribute value
I have a class hierarchy with base class Element where each derived element type may have collection of child elements.我有一个带有基本 class 元素的 class 层次结构,其中每个派生元素类型都可能具有子元素的集合。
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.没关系,不幸的是我需要摆脱
<children>
级别。 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?在此示例中,具有
FieldType
值,我是否可以序列化以返回包含“文本”的字符串,而无需实际挖掘 XmlEnumAttribute?
When I serialize FieldType value, the best serializer can do is:当我序列化 FieldType 值时,最好的序列化器可以做的是:
<?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?
或者我只需要创建读取 XmlEnumAttribute 的转换器?
I think what you're after is - without needing any custom serializers:我认为您所追求的是 - 不需要任何自定义序列化程序:
public abstract class Element
{
[XmlElement("leaf", typeof(Leaf))]
[XmlElement("container", typeof(Container))]
public List<Element> Children { set; get; }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.