ChrisCa
ChrisCa

Reputation: 11006

linq to xml - get childrem of those nodes with a certain attribute

I have the following XML structure:

<partners>
  <partner partner="xxxxxx" Id="12345">
    <email>[email protected]</email>
    <email>[email protected]</email>
  </partner>
  <partner partner="yyyyyyy" Id="32165">
    <email>[email protected]</email>
    <email>[email protected]</email>
  </partner>
</partners>

I am trying to get all the email addresses of a certain partner from the ID, but can't quite get it.

I have tried this so far:

var x = from a in xdoc.Elements("partner") where a.Attribute("Id").Value == rpId.ToString() select a.Value;

Any ideas what is wrong?

Upvotes: 0

Views: 72

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

Currently you're just selecting the text within the relevant partner elements - and you'll end up with a sequence of results.

I think you want:

var query = xdoc.Root.Elements("partner")
                .Single(x => (string) x.Attribute("Id") == rpId.ToString())
                .Elements("email")
                .Select(x => x.Value);

This will fail if there are no elements with the given ID - or more than one. If you just want to find all the email addresses within all the matching elements, you can use:

var query = xdoc.Root.Elements("partner")
                .Where(x => (string) x.Attribute("Id") == rpId.ToString())
                .Elements("email")
                .Select(x => x.Value);

EDIT: I've changed xdoc.Elements to xdoc.Root.Elements given the comments; I suspect you have:

XDocument xdoc = XDocument.Load(...);

That means that xdoc.Elements(...) can only find the root element - whereas you want to search from the root element.

Upvotes: 3

Related Questions