Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c# - 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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; }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...