27.4.4 修改XML文档
除了查询,还可以非常方便地修改XML文档。在代码清单27-12中,将查询结果中的第一个元素的title节点值,修改为"Computer Art"字符串。
代码清单27-12 修改XML文档示例
using System;
using System.Linq;
using System.Xml.Linq;
namespace ProgrammingCSharp4
class XmlHandleSample
{
public static void Main()
{
try
{
XDocument doc=XDocument.Load(@"c:\books.xml");
XElement root=doc.Element("books");
var book=(from b in root.Elements()
where b.ToString().IndexOf(“计算机”)>-1
select b).First();
book.Element("title").Value="Computer Art";
doc.Save(@"c:\books.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=“英文”>Computer Art</title>
<author>高德纳</author>
<year>1997</year>
</book>
</books>