Serializowanie obiektu do elementu z atrybutami i dziećmi
Chcę zdefiniować klasy, które będą produkować następujący xml za pomocą systemu.Xml.Serializacja.XmlSerializer. Mam problem z uzyskaniem listy elementów z atrybutami, które nie zawierają potomnego elementu "kontenera" dla elementów "elementu".
<?xml version="1.0" ?>
<myroot>
<items attr1="hello" attr2="world">
<item id="1" />
<item id="2" />
<item id="3" />
</items>
</myroot>
8
Author: abatishchev, 2011-06-28
1 answers
Z XmlSerializer
rzeczy są albo listy lub mają członków. Aby to zrobić musisz:
[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;}
}
Z przykładem:
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);
Który generuje:
<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>
Możesz usunąć xsi
/xsd
aliasy przestrzeni nazw, jeśli chcesz, oczywiście.
18
Author: Marc Gravell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-28 08:46:33
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-28 08:46:33