c#中的窄xdocument

阿尔卡迪乌什·拉塞亚

有什么方法可以切断 xDocument 的某些部分并仍然获得 xDocument?通过切断我的意思是保持选定的节点。
我有这样的 XML:

<something 1>
    <object>
        Name="The only object I need"
        <lev1>
            <lev2>
                Name= "Attribute I need"
            </lev2>
            <lev2>
                Name= "Attribute I also need"
            </lev2>
        </lev1>
    </object>
    <object>
        Name="Thing I want to remove"
        <lev1>
            <lev2>
                Name= "useless attribute"
            </lev2>
            <lev2>
                Name= "second useless atribute"
            </lev2>
        </lev1>
    </object>
</something 1>

我需要 xDocument 对象只包含 Name=“我需要的属性”的对象。我知道这很容易,但我找不到。
编辑:
我说的是很多非常巨大的 XML 文件。因此,我不能只选择要删除的内容。

乔恩·斯基特

你的意思是你只想要第一个子节点?是的,使用Remove扩展方法很简单

doc.Root.Elements().Skip(1).Remove();

样本:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        var doc = new XDocument(new XElement ("root",
            new XElement("child1", new XElement("grandchild1")),
            new XElement("child2", new XElement("grandchild2"))));

        Console.WriteLine("Document before:");
        Console.WriteLine(doc);

        doc.Root.Elements().Skip(1).Remove();

        Console.WriteLine("Document after:");
        Console.WriteLine(doc);
    }
}

输出:

Document before:
<root>
  <child1>
    <grandchild1 />
  </child1>
  <child2>
    <grandchild2 />
  </child2>
</root>
Document after:
<root>
  <child1>
    <grandchild1 />
  </child1>
</root>

为了概括这一点,您只想更改Skip调用以选择您不想保留的元素:

doc.Root
   .Elements()
   .Where(x => (string) x.Attribute("name") != "name to keep")
   .Remove();

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

引导程序中的窄列

来自分类Dev

Chrome中的图像变窄

来自分类Dev

从int到long unsigned int {}的转换变窄在C ++ 11中是不正确的

来自分类Dev

将孩子放在比自己窄的父母中

来自分类Dev

从XDocument C#中删除第n个xelement

来自分类Dev

C# XDocument 从 XML 文件中读取所有节点

来自分类Dev

为什么 C# 在 XDocument 中留下未关闭的标签?

来自分类Dev

确定XDocument中的元素

来自分类Dev

删除 XDocument 中的后代

来自分类Dev

如何在操作栏中变窄并更改颜色

来自分类Dev

使手册页变窄并在终端中居中

来自分类Dev

在xdocument中获取节点属性

来自分类Dev

编辑XDocument中的特定元素

来自分类Dev

C#XDocument XML格式

来自分类Dev

XDocument命名空间C#

来自分类Dev

使用XDocument和XElement如何在C#中向XML添加XAttribute和值

来自分类Dev

C#XDocument从XML获取所有图像,并在LongListSelector中显示它们

来自分类Dev

XDocument.Parse之后的后代命令在c#WP8中返回NULL

来自分类Dev

如何使用XDocument从c#中的复杂类型xml解析文本?

来自分类Dev

如何通过在XDocument C#中传递类型来获取节点值

来自分类Dev

字符串中的XDocument XML模式

来自分类Dev

我无法读取xdocument中的子元素

来自分类Dev

将“ XStream”保存并XDocument到文件中

来自分类Dev

C#-XDocument / linq到对象

来自分类Dev

c#使用XDocument读取XML注释

来自分类Dev

C#XML复杂查询到XDocument

来自分类Dev

使用C#和XML(XDocument)的“:”错误

来自分类Dev

C#XML复杂查询到XDocument

来自分类Dev

C# XDocument 元素/元素返回 null