使用C#中的XDocument创建XML文件

90

我有一个包含字符串的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结构?


8
请发出你已经编写的代码。人们通常不喜欢仅为你编写代码。 - Mitch Wheat
5
同意 - 实际上,这个可以用一句话非常简单地完成,但是只给你答案并不能帮助你学到很多。 - Jon Skeet
2个回答

203

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");

16
注意:如果您有需要具有“内部文本”的元素,可以像这样添加它们:new XElement("description","this is the inner text of the description element.");(类似于添加属性/值对的方式)。 - Myster
1
非常好的方法。我曾经苦恼了一会儿如何同时添加元素的属性和linq表达式。所以如果有人感兴趣,我选择:new XElement("info", new object[] { new XAttribute("foo", "great"), new XAttribute("bar", "not so great") }.Concat(list.Select(x => new XElement("child", ...)))) 适当换行后,这看起来还不错。 - Sebastian Werk

0

使用 .Save 方法意味着输出将具有 BOM,而不是所有应用程序都能接受。 如果您不想要 BOM,并且如果您不确定,则建议通过编写器传递 XDocument:

using (var writer = new XmlTextWriter(".\\your.xml", new UTF8Encoding(false)))
{
    doc.Save(writer);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接