简体   繁体   中英

C# Xml Serialization: Serialize Class properties as attributes to the parent class

[Serializable]
public class XX
{
    [XmlAttribute("name")]
    public string name{get;set;}
}

[Serializable]
[XmlRoot("tree")]
public class XY
{
    public XX Name{get;set;}

    [XmlAttribute("surname")]
    public Surname{get;set;}
}

Hi, I´m trying to serialize to XML something like these class above. My Problem is that the properties of the XX class should be serialize as attributes of the serialization of XY class, instead as XmlElement. Anyone knows if it´s posible?? To clarify here is an example of the xml file that should results:

<tree name="Jack" surname="Thompson">
</tree>

I don´t want this:

<tree surname="Thompson">
    <name>Jack</name>
</tree>

I do not think that you can do this. The structure of the XML is what tells the serializer how to work. What if you had a property marked as an attribute named name in the parent object, then the serializer would not know which name to use.

You should probably adjust your class structure to reflect the xml that you want. If "name" is just an attribute of element "tree", then ideally you would have string "name" be a property of class "XY", and class "XX" not exist at all.

If you really need those classes to exist as they do now, however, I would then suggest creating a third class to act as a surrogate, which would have a structure that matches your xml, and create a method in class XY which will translate itself into your new class. Then serialize the new class instead of XY and XX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM