LINQ XML 按属性和嵌套元素查询

LINQ XML query by attribute and nested element

我是 LINQ 新手,正在尝试按属性和后代元素值查询 XML 文件。

这是我的 XML 的片段:

<redirurl>
    <exceptionList state="FL">
        <exception>
            <plancode>ZZ</plancode>
            <url>https://zzzz.com</url>
        </exception>
    </exceptionList>    
    <exceptionList state="NC">
        <exception>
            <plancode>AA</plancode>
            <url>https://aaaa.com</url>
        </exception>
        <exception>
            <plancode>BB</plancode>
            <url>https://bbbb.com</url>
        </exception>
    </exceptionList>
</redirurl>

我正在尝试按州和计划代码检索 url 的值。比如exceptionList状态属性="NC",plancode="BB",我想得到“https://bbbb.com”的url。

这是我的代码:

var xmlFilePath = "myFilePathHere";
XElement xelement = XElement.Load(xmlFilePath );

IEnumerable<XElement> urlAddress = from el in xelement.Elements("exceptionList")
                                   where (string)el.Attribute("state") == "NC"
                                   && (string)el.Element("exception").Element("plancode") == "BB"
                                   select el;

我无法获得拯救我生命的查询权利。如果我省略查询的第三行(plancode 行),我将得到整个 exceptionList 节点作为结果。我想我可以遍历它来获取 plancode,但这似乎不是正确的做法。按原样查询不会 return 结果。我在这上面花了大约 10 个小时,做教程和查看代码示例,但我就是不明白。有人可以建议我缺少什么吗?提前致谢。

这是一个按照您的要求执行的 Linq 序列:

XDocument doc = XDocument.Parse("<redirurl><exceptionList state=\"FL\"><exception><plancode>ZZ</plancode><url>https:////zzzz.com</url></exception></exceptionList><exceptionList state=\"NC\"><exception><plancode>AA</plancode><url>https:////aaaa.com</url></exception><exception><plancode>BB</plancode><url>https:////bbbb.com</url></exception></exceptionList></redirurl>");

            var urlIWant = doc.Root.Descendants("exceptionList").Where(x => x.Attribute("state").Value == "NC").FirstOrDefault()
                .Descendants("exception").Where(z => z.Descendants("plancode").FirstOrDefault().Value == "BB")
                    .FirstOrDefault().Descendants("url").FirstOrDefault().Value;