Linq to XML可以方便地修改XML树,如添加,删除,更新和复制XML文档的内容其中包括:
1.插入:使用XNode类中的某一种添加方法可以很容易地向一个XML树添加内容.(AddAfterSelf,AddBeforeSelf)
2.更新:使用LINQ to XML更新XML相当简单.(ReplaceWith)
3.删除:使用LINQ to XML删除XML只要导航到要删除的内容调用删除方法即可.(Remove,RemoveAll)
(1)插入元素
using System;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//保存
XElement xel = new XElement(new XElement("Root",
new XElement("Person",
new XElement("Name","Huang Cong"))));
//在Hang Cong之前插入一个元素
xel.Element("Person").Element("Name").AddBeforeSelf(new XElement("Sex", "男"));
//在Hang Cong之后插入一个元素
xel.Element("Person").Element("Name").AddAfterSelf(new XElement("Age", 22));
Console.WriteLine(xel);
}
}
}
(2)更新元素
using System;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//保存
XElement xel = new XElement(new XElement("Root",
new XElement("Person",
new XElement("Name", "Huang Cong"),
new XElement("Sex", "男"),
new XElement("Age", 22))));
//更新某个元素
xel.Element("Person").Element("Name").ReplaceWith(new XElement("Name","Li Si"));
Console.WriteLine(xel);
Console.WriteLine("--------------------------");
//更新一个元素以及子节点
xel.Element("Person").ReplaceWith(new XElement("Person",
new XElement("Name", "Zhang San"),
new XElement("Sex", "女"),
new XElement("Age", 23)));
Console.WriteLine(xel);
}
}
}
(3)删除元素
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黄聪 , Ltd .
//-----------------------------------------------------------
using System;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//保存
XElement xel = new XElement(new XElement("Root",
new XElement("Person",
new XElement("Name", "Huang Cong"),
new XElement("Sex", "男"),
new XElement("Age", 22))));
//从父节点删除该元素,包括该元素下的所有子节点
xel.Element("Person").Element("Sex").Remove();
Console.WriteLine(xel);
Console.WriteLine("--------------------------");
//删除某个元素下的所有子节点
xel.Element("Person").RemoveAll();
Console.WriteLine(xel);
}
}
}