0

Given an XML file like:

<?xml version="1.0" encoding="utf-8"?>
<Root>
   <Policy id="832cbfc6-a451-4d77-a995-4ceb9d3bbe01" username ="DCassidy">     
      <Title>Test 1</Title>    
  </Policy>
  <Policy id="832cbfc6-a451-4d77-a995-4ceb9d3bbe02" userName ="DCassidy">
    <Title>Test 2</Title>
 </Policy>........and so on

Is it possible to use LINQ to XML to return all the 'Policy' elements and their containing elements without having to specify each element thing like:

var subset = doc.Elements("Policy").SelectMany(x => new[] { x.Element("Title").Value });

I need to be able to dynamically add elements to the file, filter and return a subset.

preferabbly, returning a collection of XElemets so that later I can call:

subset.CreateReader() on.

EDIT

To be clearer. I will want to return ALL Policy objects and their descendants based on the username attribute. I the want to take that subset and use CreateReader() on it.

Can someone help please?

Thanks

davy
  • 4,474
  • 10
  • 48
  • 71

3 Answers3

0

Use the Elements() method without specifying an element name to get all direct descendants:

XDocument.Root.Elements()

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You can use the Elements overload that does not specify a name to get all the child elements.

var xml = @"
<Root>
   <Policy id='832cbfc6-a451-4d77-a995-4ceb9d3bbe01' username ='DCassidy'>     
      <Title>Test 1</Title>    
  </Policy>
  <Policy id='832cbfc6-a451-4d77-a995-4ceb9d3bbe02' userName ='DCassidy'>
    <Title>Test 2</Title>
 </Policy>
</Root>
";
var xElement = XElement.Parse(xml);
var subset = xElement.Elements("Policy").SelectMany(e => e.Elements());

The subset is an IEnumerable<XElement> whose contents are:

<Title>Test 1</Title> 
<Title>Test 2</Title> 
qxn
  • 17,162
  • 3
  • 49
  • 72
0

It's not really clear what you mean, but perhaps:

var subset = doc.Elements("Policy").Descendants();

or

var subset = doc.Elements("Policy").DescendantsAndSelf();

This will get all descendants, not just direct ones. If you could be clearer about exactly what you're trying to achieve, that would help.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194