[英]how to class wrap a list in c# for xml serializing
一个类如何在 c# 中包装一个列表以进行 xml 序列化? 我想添加一个根。 也许类包装器不是一个好主意。 我应该使用不同的 aprouch 吗?
当我序列化以下类时:
public class Parts
{
//main class
[XmlElement("Access")]
public List<Access> AccessDB = new List<Access>
{
new Access
{
Items = new[] {
new Component { Name = "dbName" }
,new Component { Name = "DbElement" } }
, Scope = "GlobalVariable", UId = "21"
},
new Access
{
Items = new[] {
new Component { Name = "TagName" } }
, Scope = "GlobalVariable", UId = "22"
}
};
}
我得到:
<Parts>
<Access Scope="Scope" UId="21">
<Symbol>
<Component Name="Name" />
<Component Name="Name" />
</Symbol>
</Access>
<Access Scope="Scope" UId="22">
<Symbol>
<Component Name="Name" />
</Symbol>
</Access>
<Part Name="PartName" UId="23" />
</Parts>
但我需要的是:
<myroot>
<Parts>
<Access Scope="Scope" UId="21">
<Symbol>
<Component Name="Name" />
<Component Name="Name" />
</Symbol>
</Access>
<Access Scope="Scope" UId="22">
<Symbol>
<Component Name="Name" />
</Symbol>
</Access>
<Part Name="PartName" UId="23" />
</Parts>
</myroot>
非常欢迎任何建议!
如果myroot
元素只需要出现在xml
输出中,您可以在序列化期间添加它。
使用XmlWriter
作为序列化的输出目标。
在序列化Parts
实例之前,您使用XmlWriter
创建myroot
元素。
XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
StringBuilder stringBuilder = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
xmlWriter.WriteStartElement("myroot"); // Writes <myroot>
var serializer = new XmlSerializer(typeof(Parts));
var parts = new Parts();
serializer.Serialize(xmlWriter, parts);
xmlWriter.WriteEndElement(); // Writes </myroot>
}
我发现也可以类包装其他类,但类的实例必须是公共的。 在代码中:
public class myRoot
{
public Parts Parts = new Parts();
}
然后序列化类myRoot
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.