davy
davy

Reputation: 4562

How to return a subset of XElements inside parent XElement

If I have xml such as the following:

<ValidationResults>
  <ValidationResult>     
    <Scheme>Scheme A</Scheme>
  </ValidationResult>
  <ValidationResult>  
    <Scheme>Scheme B</Scheme>
  </ValidationResult>   

I want to query it using Linq to Xml so that I return:

<ValidationResults>
  <ValidationResult>     
    <Scheme>Scheme A</Scheme>
  </ValidationResult>     
</ValidationResults>

If I do something like this:

....Element("ValidationResults").Elements("ValidaitonResult")
                                .Where(x => x.Element("Scheme").Value == "Scheme A");

I return only:

 <ValidationResult>     
    <Scheme>Scheme A</Scheme>
 </ValidationResult>  

Then I am currently creating the parent again and adding the children to it, which does not seem correct:

var parentElement = new XElement("ValidationResults");
var childElements = //get as above

parentElement.Add(childElements);

How do I return a queried subset of elements inside it's original parent?

Upvotes: 0

Views: 251

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503869

Your current approach seems the simplest one to me, although it could be done in a single statement as:

var element = new XElement("ValidationResults",
    doc.Element("ValidationResults")
       .Elements("ValidationResult")
       .Where(x => x.Element("Scheme").Value == "Scheme A")));

Assuming you don't want to modify your existing document, you either have to come up with a new "root" validation results element like this or you need to clone the existing one and remove anything you're not interested in. Just copying in the elements you do want seems simpler than pruning out what you don't want.

Of course, you could avoid the duplication of the string literal pretty easily - extract that as a constant somewhere, so you can make sure that you're creating a new element with the same name as the old one.

Upvotes: 1

Related Questions