dhamilton
dhamilton

Reputation: 173

Linq to XML Questions: Why is my query not working

At the point of my issue i have the following XML in an XElement. There can be many of these "Identifiers" nodes in the full XML and my navigation is working to this point.

    <Identifiers>
      <identifier>
        <Type>MR</Type>
        <Value>123321</Value>
        <Authority></Authority>
      </identifier>
      <identifier>
        <Type>AN</Type>
        <Value>123321-01</Value>
        <Authority></Authority>
      </identifier>
      <identifier>
        <Type>PN</Type>
        <Value>123321</Value>
        <Authority></Authority>
      </identifier>
    </Identifiers>

Here the is the Linq-To-XML:

    id = xd.Root.Element("Patient");
    id = id.Element("Identifiers"); //At this point "id" contains the above XML.
    id = id.Elements("Identifier").FirstOrDefault(x => x.Element("Type").Value == "AN");

Is the last statement where it falls apart and is returning null.

What am I missing here?

Upvotes: 1

Views: 103

Answers (2)

mellowgeek
mellowgeek

Reputation: 305

Since XML is case sensitive, trying replacing "Identifier" in your last statement with "identifier".

Upvotes: 6

Matt Cashatt
Matt Cashatt

Reputation: 24208

Assuming that xd is your XDocument, then try this:

xd.Descendents("identifier").FirstOrDefault(x => x.Element("Type").Value == "AN");

In fact, if you only expect a single "AN" value for type in your document, then you can do this:

 xd.Descendents("Type").FirstOrDefault(x => x.Value.Equals("AN"));

Or if you possibly have many "Type" with value "AN":

xd.Descendents("Type").Where(x => x.Value.Equals("AN"));

Upvotes: 1

Related Questions