[英]Serialize List Elements in XML without class name
I the following class: 我下面的课:
public class Family
{
public List<ChildAge> childAges { get; set; }
}
Now the ChildAge looks like this: 现在,ChildAge如下所示:
public class ChildAge
{
public int Age { get; set; }
}
When I serialize this to XML I get: 当我将此序列化为XML时,我得到:
<root>
<Family>
<ChildAges>
<ChildAge>
<Age>10</Age>
</ChildAge>
<ChildAge>
<Age>8</Age>
</ChildAge>
</ChildAges>
</Family>
</root>
What do I need to change to get this: 我需要更改以获得以下内容:
<root>
<Family>
<ChildAges>
<Age>10</Age>
<Age>8</Age>
</ChildAges>
</Family>
<root>
Thanks! 谢谢!
You can do it (and much more) by providing your own implementation of WriteXml... 您可以通过提供自己的WriteXml实现来做到这一点(以及更多)。
Please take a look at the following piece of code. 请看下面的代码。
public class Family : IXmlSerializable
{
public List<ChildAge> childAges { get; set; }
public void WriteXml(XmlWriter writer)
{
foreach(ChildAge ca in childAges)
writer.WriteElementString("Age", ca.Age.ToString());
}
public void ReadXml(XmlReader reader)
{
// [...]
}
public XmlSchema GetSchema()
{
return (null);
}
}
public class ChildAge
{
public int Age { get; set; }
}
public class Program
{
static void Main(string[] args)
{
Family f = new Family();
f.childAges = new List<ChildAge>();
f.childAges.Add(new ChildAge() { Age = 10 });
f.childAges.Add(new ChildAge() { Age = 8 });
XmlSerializer xs = new XmlSerializer(typeof(Family));
XmlSerializerNamespaces xmlnsEmpty;
xmlnsEmpty = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.OmitXmlDeclaration = true;
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlTextWriter.Create(sb, writerSettings);
xs.Serialize(writer, f, xmlnsEmpty);
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
}
Your problem will begin once you'll have more properties to serialize under "childage" you could simply use a list and the following annotations: 一旦在“子项”下有更多要序列化的属性,您的问题就会开始,您只需使用列表和以下注释即可:
[XmlArray("ChildAges")]
[XmlArrayItem("Age")]
List<int> ChildrenAges { get; set; }
and you're pretty much done 你已经完成了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.