views:

108

answers:

1

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  A: 

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>
nithins
@nithins - Almost tempted to ruin your very nice score (404) with an upvote :), but shouldn't `nodes.Remove()` actually be more along the lines of `nodes.ToList().ForEach(e => e.Remove())` ? (Also, for more nitpicking, I think `nodes` will never be null, just possibly empty)
Alex Paven