27.4.2 创建XML文档
代码清单27-10 使用LINQ to XML创建XML文档
using System;
using System.Xml.Linq;
namespace ProgrammingCSharp4
{
class XmlHandleSample
{
public static void Main()
{
try
{
XDocument xml=new XDocument(
new XDeclaration("1.0","utf-8","yes"),
new XComment(“本XML文档使用LINQ TO XML创建”),
new XElement("books",
new XElement("book",
new XAttribute("category",“计算机”),
new XElement("title",“计算机程序设计艺术(第一卷,第三版)”,
new XAttribute("lang",“英文”)),
new XElement("author",“高德纳”),
new XElement("year","1997")
)
)
);
xml.Save(@"c:\books.xml");
Console.WriteLine(“成功生成XML文档。”);
}
catch(System.Exception)
{
Console.WriteLine(“处理过程出错,请检查。”);
throw;
}
}
}
}
上述代码生成的XML文档(c:\books.xml)内容如下:
<?xml version="1.0"encoding="utf-8"standalone="yes"?>
<!—本XML文档使用LINQ TO XML创建—>
<books>
<book category=“计算机”>
<title lang=“英文”>计算机程序设计艺术(第一卷,第三版)</title>
<author>高德纳</author>
<year>1997</year>
</book>
</books>