với XmlSerializer
điều là hoặc danh sách hoặc họ có các thành viên. Để làm điều đó bạn cần:
[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;}
}
với ví dụ:
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);
mà tạo ra:
<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>
bạn có thể loại bỏ các bí danh namespace xsi
/xsd
nếu bạn muốn, tất nhiên.
Nguồn
2011-06-28 08:46:33
Nếu hiểu biết của tôi là chính xác, bạn không thể tạo lớp Hạng mục có tập hợp hạng mục? – Novice
Đúng vậy, nhưng phần tử của mục phải có các thuộc tính. – Sprintstar
Có, chúng tôi không thể xác định các thuộc tính khác cũng nằm trong lớp mục? – Novice