Linq到Xml,查询中的过滤器元素(C#) [英] Linq to Xml, Filter Element from Query (C#)

查看:47
本文介绍了Linq到Xml,查询中的过滤器元素(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图查询xml文档并遍历结果减去特定元素.理想情况下,我想在查询中实现此目的,而不是在迭代之前或迭代期间将其从集合中删除.

I'm simply trying to query an xml document and iterate over the results minus specific elements. Ideally I would like to achieve this in the query rather than removing it from the collection before or during iteration.

<body>
       Stuff I want
  <element>
       Stuff I dont want
  </element>
</body>

我尝试过类似的方法,但是没有运气....

I tried something along these lines but had no luck....

        var doc = XDocument.Load("document.xml");
        var results = doc.Descendants("body")
                         .Where(x => x.Name != "element")

我当然不喜欢使用XML,如果已经回答了,我深表歉意.

I'm certainly out of my element using XML, apologies if this has been answered already.

推荐答案

一种方法是获取文档,查询不需要的内容,然后对它们进行.Remove().例如,如果您使用的是XML,则如下所示:

One way to do this would be to grab the document, query for the stuff you don't want, and then .Remove() them. For example, if you're XML looked something like the following:

<body>
    Stuff I want
    <element>Stuff I dont want</element>
    <element>Stuff I want</element>
</body>

您可以执行以下代码来更改文档的所有内容,但包含我不想要的东西"的内容除外:

You could do the following code to alter the document with everything except for the containing "Stuff I don't want":

        var doc = XDocument.Load("foo.xml");

        IEnumerable<XElement> nodes =
                                from node in doc.Descendants("element")
                                where node.Value == "Stuff I dont want"
                                select node;

        if (nodes != null)
        {
            nodes.Remove();
        }

这会在您的文档中产生以下内容:

Which would then yield the following in your doc:

<body>
    Stuff I want
    <element>Stuff I want</element>
</body>

这篇关于Linq到Xml,查询中的过滤器元素(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆