[英]XML file creation using XDocument in C#
我有一個List<string>
“sampleList”,其中包含
Data1
Data2
Data3...
文件結構就像
<file>
<name filename="sample"/>
<date modified =" "/>
<info>
<data value="Data1"/>
<data value="Data2"/>
<data value="Data3"/>
</info>
</file>
我目前正在使用XmlDocument來執行此操作。
例:
List<string> lst;
XmlDocument XD = new XmlDocument();
XmlElement root = XD.CreateElement("file");
XmlElement nm = XD.CreateElement("name");
nm.SetAttribute("filename", "Sample");
root.AppendChild(nm);
XmlElement date = XD.CreateElement("date");
date.SetAttribute("modified", DateTime.Now.ToString());
root.AppendChild(date);
XmlElement info = XD.CreateElement("info");
for (int i = 0; i < lst.Count; i++)
{
XmlElement da = XD.CreateElement("data");
da.SetAttribute("value",lst[i]);
info.AppendChild(da);
}
root.AppendChild(info);
XD.AppendChild(root);
XD.Save("Sample.xml");
如何使用XDocument創建相同的XML結構?
LINQ to XML通過三個功能使這更加簡單:
所以你可以這樣做:
void Main()
{
List<string> list = new List<string>
{
"Data1", "Data2", "Data3"
};
XDocument doc =
new XDocument(
new XElement("file",
new XElement("name", new XAttribute("filename", "sample")),
new XElement("date", new XAttribute("modified", DateTime.Now)),
new XElement("info",
list.Select(x => new XElement("data", new XAttribute("value", x)))
)
)
);
doc.Save("Sample.xml");
}
我故意使用這種代碼布局來使代碼本身反映文檔的結構。
如果你想要一個包含文本節點的元素,你可以通過將文本作為另一個構造函數參數傳入來構造它:
// Constructs <element>text within element</element>
XElement element = new XElement("element", "text within element");
使用.Save方法意味着輸出將具有BOM,並非所有應用程序都滿意。 如果你不想要BOM,如果你不確定那么我建議你不要,那么通過一個編寫器傳遞XDocument:
using (var writer = new XmlTextWriter(".\\your.xml", new UTF8Encoding(false)))
{
doc.Save(writer);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.