Linq to XML问题:为什么我的查询不能工作

时间:2022-03-08 00:11:30

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.

在我的问题中,我在XElement中包含以下XML。在完整的XML中可以有许多这样的“标识符”节点,我的导航就到这里了。

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

这里是链接到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.

是最后的语句,它会崩溃并返回null。

What am I missing here?

我错过了什么?

2 个解决方案

#1


6  

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

由于XML是区分大小写的,所以尝试用“标识符”替换上一条语句中的“标识符”。

#2


1  

Assuming that xd is your XDocument, then try this:

假设xd是您的XDocument,那么尝试以下操作:

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:

事实上,如果您只希望在文档中键入一个“AN”值,那么您可以这样做:

 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"));

#1


6  

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

由于XML是区分大小写的,所以尝试用“标识符”替换上一条语句中的“标识符”。

#2


1  

Assuming that xd is your XDocument, then try this:

假设xd是您的XDocument,那么尝试以下操作:

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:

事实上,如果您只希望在文档中键入一个“AN”值,那么您可以这样做:

 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"));