1

我对 XML 文件的 linq 查询遇到了一个稍微令人困惑的问题。它按属性值正确返回节点之一 ( GB)。但是,当我提供不同的属性值时,例如:JE我收到一个sequence contains no elements错误,但该元素显然存在于 XML 文档中?

这是我的查询:

return (from n in xml.Descendants("postalCodeData")
        where n.Element("postCodeRegex").Attribute("territoryId").Value == isoCode
        select n.Element("postCodeRegex").Value).Single().ToString();

以下是一些示例 XML 数据:

<postalCodeData>
  <postCodeRegex territoryId="GB" >GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}</postCodeRegex>
  <postCodeRegex territoryId="JE" >JE\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}</postCodeRegex>
  <postCodeRegex territoryId="GG" >GY\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}</postCodeRegex>
</postalCodeData>

谁能发现我在这里做错了什么?为什么这适用于GB其他人而不适用于其他人?

4

2 回答 2

2
n.Element("postCodeRegex") 

will return the first element of that type, and only its "territoryId" will be examined.

instead replace the where clause with this this :

 where n.Elements("postCodeRegex").Any(element=>element.Attribute("territoryId").Value == isoCode)

EDIT: Ok, so you wanted the matching postcoderegex item. I thought you wanted the first element that was bundled with a match. Then the solution is much easier.

return (from n in xml.Descendants("postCodeRegex")
  where n.Attribute("territoryId").Value == isoCode
  select n.ToString();
于 2013-06-21T15:38:21.537 回答
0

解决了,我只检查第一个匹配的元素:

return (from n in xml.Descendants("postalCodeData").Elements("postCodeRegex")
        where n.Attribute("territoryId").Value == isoCode
        select n.Value).Single().ToString();
于 2013-06-21T15:48:37.787 回答