Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - Serialize object to element with attributes and children

I wish to define classes that will produce the following xml using System.Xml.Serialization.XmlSerializer. I am struggling to get the items list, with attributes that does not contain a child 'container' element for 'item' elements.

<?xml version="1.0" ?>
<myroot>
   <items attr1="hello" attr2="world">
      <item id="1" />
      <item id="2" />
      <item id="3" />
   </items>
</myroot>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

with XmlSerializer things are either lists or they have members. To do that you need:

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

with example:

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

which generates:

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

you can remove the xsi/xsd namespace aliases if you want, of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...