[英]convert List of string array into xml
我需要將數組列表轉換為 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 文件格式非常陌生。
這是解決方案。 請注意, Zip
方法有第二個參數,它允許您為元組字段名稱實現更合適的名稱,而不是First
和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>
您正在尋找的是所謂的 XML 序列化。 有一個很好的介紹可以在: https ://docs.microsoft.com/en-us/dotnet/standard/serialization/introducing-xml-serialization
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.