繁体   English   中英

将字符串数组列表转换为xml

[英]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方法有第二个参数,它允许您为元组字段名称实现更合适的名称,而不是FirstSecond

编码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM