[英]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.