我需要將陣列串列轉換為 xml。在串列中,第一個物件是 xml 的元素,從第二個物件開始,它是元素的值。
例如:
list[0]={"firstname","lastname","age","empid"}
list[1]={"john","maxwell","31","101"}
list[2]={"max","lee","45","102"}
現在使用上面的串列我需要創建一個 XML 檔案,如上所述 list[0] 需要用作 XML 元素,而 list[1] & list[2] 是這些元素的值。最終的 XML 看起來像這樣:
<?xml version="1.0" encoding="UTF-8"?>
<EmployeeRecords>
<Employee>
<firstname>john</firstname>
<lastname>maxwell</lastname>
<age>31</age>
<empid>101</empid>
</Employee>
<Employee>
<firstname>Max</firstname>
<lastname>lee</lastname>
<dob>45</dob>
<empid>102</empid>
</Employee>
</EmployeeRecords>
我嘗試過使用XELement類,但我無法理解如何在其中動態傳遞元素名稱。
XElement xmlout = new XElement("EmployeeRecords", list.Select(i => new XElement("Employee", i.Select(tag=>new XElement("Employee",tag)))));
我也嘗試過使用動態創建元素,XmlDocument但它們也不起作用。請對此進行指導,因為我對 XML 檔案格式非常陌生。
uj5u.com熱心網友回復:
這是解決方案。請注意,Zip方法的第二個引數允許您為元組欄位名稱實作更合適的名稱,而不是Firstand Second。
編碼
using System.Xml.Linq;
string[][] data =
{
new[] { "firstname", "lastname", "age", "empid" },
new[] { "john", "maxwell", "31", "101" },
new[] { "max", "lee", "45", "102" }
};
var xmlout = new XElement("EmployeeRecords",
data.Skip(1).Select(_ => new XElement("Employee",
// Zip joins two lists - names at data[0] and values, which are in _
data[0].Zip(_).Select(_=>new XElement(_.First, _.Second))
)))
.ToString();
Console.Write(xmlout);
輸出
<EmployeeRecords>
<Employee>
<firstname>john</firstname>
<lastname>maxwell</lastname>
<age>31</age>
<empid>101</empid>
</Employee>
<Employee>
<firstname>max</firstname>
<lastname>lee</lastname>
<age>45</age>
<empid>102</empid>
</Employee>
</EmployeeRecords>
uj5u.com熱心網友回復:
您正在尋找的是所謂的 XML 序列化。有一個很好的介紹可以在:https ://docs.microsoft.com/en-us/dotnet/standard/serialization/introducing-xml-serialization
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/476305.html
上一篇:如何只選擇頂級標簽?
