【问题标题】:Serialize Class to flat XML将类序列化为平面 XML
【发布时间】:2017-05-09 00:16:32
【问题描述】:

本质上,我需要将 C# 对象序列化为具有完全不同的 xml 结构和不同类/节点名称的 xml 文档。 C#类的结构是:

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

假设我们的项目是汽车。这序列化为

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

但我需要将其序列化为:

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

我目前正在使用 IXmlSerializable 来尝试指定架构。这样做的最佳方法是什么?我应该转换为第二个自定义对象吗?

【问题讨论】:

  • 手动考虑 DOM xml 写作?
  • 我要么更改您当前的模型,要么将其复制到与您的输出匹配的新模型

标签: c# xml serialization


【解决方案1】:

试试这个:

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

另外,最好使用nameof 而不是硬编码的文字。

[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();
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多