Linq to Xml, Filter Element from Query (C#)

一世执手 提交于 2019-12-24 10:35:39

问题


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")

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


回答1:


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>


来源:https://stackoverflow.com/questions/3760764/linq-to-xml-filter-element-from-query-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!