c# - 将对象序列化为具有属性和子元素的元素

标签 c# xml-serialization xmlserializer

我希望定义将使用 System.Xml.Serialization.XmlSerializer 生成以下 xml 的类。我正在努力获取项目列表,其中的属性不包含“项目”元素的子“容器”元素。

<?xml version="1.0" ?>
<myroot>
   <items attr1="hello" attr2="world">
      <item id="1" />
      <item id="2" />
      <item id="3" />
   </items>
</myroot>

最佳答案

使用 XmlSerializer 的东西是或者列表或者他们有成员。为此,您需要:

[XmlRoot("myroot")]
public class MyRoot {
    [XmlElement("items")]
    public MyListWrapper Items {get;set;}
}

public class MyListWrapper {
    [XmlAttribute("attr1")]
    public string Attribute1 {get;set;}
    [XmlAttribute("attr2")]
    public string Attribute2 {get;set;}
    [XmlElement("item")]
    public List<MyItem> Items {get;set;}
}
public class MyItem {
    [XmlAttribute("id")]
    public int Id {get;set;}
}

举例:

var ser = new XmlSerializer(typeof(MyRoot));
var obj = new MyRoot
{
    Items = new MyListWrapper
    {
        Attribute1 = "hello",
        Attribute2 = "world",
        Items = new List<MyItem>
        {
            new MyItem { Id = 1},
            new MyItem { Id = 2},
            new MyItem { Id = 3}
        }
    }
};
ser.Serialize(Console.Out, obj);

生成:

<myroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://
www.w3.org/2001/XMLSchema">
  <items attr1="hello" attr2="world">
    <item id="1" />
    <item id="2" />
    <item id="3" />
  </items>
</myroot>

当然,如果需要,您可以删除 xsi/xsd 命名空间别名。

关于c# - 将对象序列化为具有属性和子元素的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6503762/

相关文章:

c# - 无法测试的 Braintree API : Should I alter the source code or individually wrap every class?

c# - 使用XmlArray反序列化xml文件?

c# - 将类转换为 XML 到字符串

c# - 反序列化 XML 文件而不将其全部加载到内存中

c# - 具有默认值的 XmlSerializer 和 List<T>

c# - XmlSerializer 将空格替换为 0x0020(十六进制值)

c# - 无法将 xml 反序列化为 List<T>

c# - ar-sa 文化的预期日期时间字符串是什么?

c#创建一个不需要输入默认参数的方法

c# - File.ReadLines 上的 IEnumerable.Take(0) 似乎没有处理/关闭文件句柄