Spr*_*tar 8 c# xml-serialization xmlserializer
我希望使用System.Xml.Serialization.XmlSerializer定义将生成以下xml的类.我正在努力获取项目列表,其中的属性不包含'item'元素的子'container'元素.
<?xml version="1.0" ?>
<myroot>
<items attr1="hello" attr2="world">
<item id="1" />
<item id="2" />
<item id="3" />
</items>
</myroot>
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 18
有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;}
}
Run Code Online (Sandbox Code Playgroud)
用例子:
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);
Run Code Online (Sandbox Code Playgroud)
产生:
<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>
Run Code Online (Sandbox Code Playgroud)
当然,如果需要,可以删除xsi/ xsdnamespace别名.