繁体   English   中英

将 object 序列化为具有属性和子元素的元素

[英]Serialize object to element with attributes and children

我希望使用 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命名空间别名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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