您的位置:知识库 » 数据库

Linq To Xml学习 - 3.查询、更新、删除

作者: Q.Lee.lulu  来源: 博客园  发布时间: 2008-09-23 17:13  阅读: 45201 次  推荐: 6   原文链接   [收藏]  

XNode.ReplaceWith 方法

使用指定的内容替换此节点。

XElement xmlTree = new XElement("Root",
    new XElement("Child1", "child1 content"),
    new XElement("Child2", "child2 content"),
    new XElement("Child3", "child3 content"),
    new XElement("Child4", "child4 content"),
    new XElement("Child5", "child5 content")
);
XElement child3 = xmlTree.Element("Child3");
child3.ReplaceWith(
    new XElement("NewChild", "new content")
);
Console.WriteLine(xmlTree);

输出结果:

<Root>
  <Child1>child1 contentChild1>
  <Child2>child2 contentChild2>
  <NewChild>new contentNewChild>
  <Child4>child4 contentChild4>
  <Child5>child5 contentChild5>
Root>

从 XML 树中移除元素、属性和节点

可以修改 XML 树,移除元素、属性和其他类型的节点。

从 XML 文档中移除单个元素或单个属性的操作非常简单。 但是,若要移除多个元素或属性的集合,则应首先将一个集合具体化为一个列表,然后从该列表中删除相应元素或属性。 最好的方法是使用 Remove 扩展方法,该方法可以实现此操作。

这么做的主要原因在于,从 XML 树检索的大多数集合都是用延迟执行生成的。 如果不首先将集合具体化为列表,或者不使用扩展方法,则可能会遇到某类 Bug。

image

示例:

此示例演示三种移除元素的方法。 第一种,移除单个元素。 第二种,检索元素的集合,使用 Enumerable.ToList<(Of <(TSource>)>) 运算符将它们具体化,然后移除集合。 最后一种,检索元素的集合,使用 Remove 扩展方法移除元素。

XElement root = XElement.Parse(@" 
");
root.Element("Child1").Element("GrandChild1").Remove();
root.Element("Child2").Elements().ToList().Remove();
root.Element("Child3").Elements().Remove();
Console.WriteLine(root);

输出结果为:

<Root>
  <Child1>
    <GrandChild2 />
    <GrandChild3 />
  Child1>
  <Child2 />
  <Child3 />
Root>
6
0
 
标签:linq xml

数据库热门文章

    数据库最新文章

      最新新闻

        热门新闻