c# - 具有不同节点路径的 XPath

标签 c# xml xpath

我正在尝试提出正确的 XPath,以便根据不属于要使用 C# 中的 XDocument.XPathSelectElement 方法选择的 XPath 的条件来获取节点。

假设我有以下 XML。

<Root>
    <Parties>
        <Party>
            <Person>
                <Name>Bob Smith</Name>
            </Person>
            <Role>
                <Type>Borrower</Type>
            </Role>
        </Party>
        <Party>
            <Person>
                <Name>Mary Smith</Name>
            </Person>
            <Role>
                <Type>CoBorrower</Type>
            </Role>
        </Party>
    </Parties>
</Root>

所以我想要得到的是

的值
//Root/Parties/Party/Person/Name 

哪里

//Root/Parties/Party/Role/Type 

是“借款人”。

根据我在发布问题之前的研究,我认为以下方法可能有效,但没有运气。

XDocument xDoc = XDocument.Parse(xml);
var elm = xDoc.XPathSelectElement("//Root/Parties/Party[./Role/[Type = 'Borrower']/Person/Name");

但是这段代码给了我以下异常:

An unhandled exception of type 'System.Xml.XPath.XPathException' occurred in System.Xml.dll
Additional information: Expression must evaluate to a node-set.

最佳答案

使用此 XPath 表达式:

//Root/Parties/Party[Role/Type/text() = 'Borrower']/Person/Name

它会给你想要的结果

Bob Smith

关于c# - 具有不同节点路径的 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42494600/

相关文章:

java - XPATH 仅选择第一级子级

c# - 关于 DataContractSerializer 构造类实例的奇怪(对我来说)行为不是来自函数的 'returned'

PHP在post请求中读取xml

php - 查找 DomNode/Xpath 子元素的索引位置

html - 一个 Xpath 表达式在 selenium 中不起作用,但在 Firefox 中起作用

android - 未使用 Android Studio 选择渲染目标

c# - 使用 Visual Team Services 构建和发布服务器部署 Azure Function

c# - 通过 EWS 和 C# 访问没有邮箱的资源日历

c# - 绑定(bind)到静态类实例中的属性

java - 如何将 UTF-8 字符串转换为日语或任何其他语言的 IText PDF?