简体   繁体   中英

Serialize Class to flat XML

Essentially, I need to serialize a C# object to an xml document with an entirely different xml structure and different class/node names. The structure of the C# class is:

public class Root 
  {
     public item item {get; set}
  }

public class item
  {
     public string name {get; set}
     public color[] color
  }    

public class color
  {
     public string itemColor {get; set}
  }

Lets say our item is a car. This serializes to

<Root>
   <item>
        <name>car</name>
        <color>
             <itemColor>red</itemColor>
             <itemColor>blue</itemColor>
             <itemColor>gree</itemColor>
        </Color>
    </item>
</Root>

But I need this to serialize to:

<Root>
   <item>
        <name>car</name>
        <itemColor>red</itemColor>
   </item>
        <name>car</name>
        <itemColor>blue</itemColor>
   </item>
   <item>
        <name>car</name>
        <itemColor>green</itemColor>
   </item>
</Root>

I'm currently using IXmlSerializable to try and specify a schema. What is the optimal way of doing this? Should I convert to a second custom object?

Try this:

public class Root
{
    [XmlIgnore]
    public item item { get; set; }

    [EditorBrowsable(EditorBrowsableState.Never)]
    [XmlAnyElement("item")]
    public List<XElement> _item
    {
        get
        {
            return item.color.Select(i =>
                new XElement("item",
                    new XElement("name", item.name),
                    new XElement("itemColor", i.itemColor)
                )).ToList();
        }
    }
}

public class item
{
    public string name { get; set; }
    public color[] color;
}

public class color
{
    public string itemColor { get; set; }
}

Also, it would be better to use nameof instead of hardcoded literals.

[XmlAnyElement(nameof(item))]
public List<XElement> _item
{
    get
    {
        return item.color.Select(i =>
            new XElement(nameof(item),
                new XElement(nameof(item.name), item.name),
                new XElement(nameof(i.itemColor), i.itemColor)
            )).ToList();
    }
}

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