序列化对象元素和属性和儿童 [英] Serialize object to element with attributes and children
本文介绍了序列化对象元素和属性和儿童的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要定义将产生使用System.Xml.Serialization.XmlSerializer以下XML类。我努力获得的项目清单,与不包含'项'元素的孩子容器元素的属性。
<?XML版本=1.0>?;
< myroot>
<项目ATTR1 =你好attR2位=世界>
<项目ID =1/>
<项目编号=2/>
<项目ID =3/>
< /项目>
< / myroot>
解决方案
与的XmlSerializer
东西的的或者的名单或的他们的成员。要做到这一点,你需要:
[XmlRoot(myroot)]
公共类MyRoot {
[的XmlElement(项目)]
公共MyListWrapper项目{获得;设置;}
}
公共类MyListWrapper {
[XmlAttribute(ATTR1)]
公共字符串ATTRIBUTE1 {获取;设置;}
[XmlAttribute(attR2位)]
公共字符串Attribute2 {获取;集;}
[的XmlElement(项目)]
公开名单< MyItem>项目{获得;设置;}
}
公共类MyItem {
[XmlAttribute(ID)]
公众诠释标识{获取;设置;}
}
与例如:
VAR SER =新的XmlSerializer(typeof运算(MyRoot));
VAR OBJ =新MyRoot
{
项=新MyListWrapper
{
ATTRIBUTE1 =你好,
Attribute2 =世界,
=项新的List< MyItem>
{
新MyItem {n = 1},
新MyItem {ID = 2},
新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 / XML模式>
<项目ATTR1 =你好attR2位=世界>
<项目ID =1/>
<项目编号=2/>
<项目ID =3/>
< /项目>
< / myroot>
您可以删除 XSI
/ XSD
命名空间的别名,如果你想要的,当然。
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>
解决方案
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.
这篇关于序列化对象元素和属性和儿童的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文