在C#中使用的XDocument XML文件的创建 [英] XML file creation using XDocument in C#

查看:506
本文介绍了在C#中使用的XDocument XML文件的创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表与LT;串> sampleList,其中包含

I have a List<string> "sampleList" which contains

Data1
Data2
Data3...

文件结构是像

<file>
   <name filename="sample"/>
   <date modified ="  "/>
   <info>
     <data value="Data1"/> 
     <data value="Data2"/>
     <data value="Data3"/>
   </info>
</file>

我目前使用XmlDocument的做到这一点。

I'm currently using XmlDocument to do this.

例如:

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结构?

How can I create the same XML structure using XDocument?

推荐答案

的LINQ to XML允许这要简单得多,通过三个特点:

LINQ to XML allows this to be much simpler, through three features:


  • 您可以构造一个对象不知道该文档是的一部分

  • 您可以构造一个对象,并提供儿童作为参数

  • 如果一种说法是迭代的,它会遍历

所以,在这里你可以这样做:

So here you can just do:

List<string> list = ...;

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

我用这个code布局故意使code本身反映文档的结构。

I've used this code layout deliberately to make the code itself reflect the structure of the document.

这篇关于在C#中使用的XDocument XML文件的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆