【问题标题】:XPath with different node path具有不同节点路径的 XPath
【发布时间】:2017-02-27 19:54:12
【问题描述】:

我正在尝试根据不属于要使用 C# 中的 XDocument.XPathSelectElement 方法选择的 XPath 的条件来获取节点的正确 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");

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

System.Xml.dll 中出现“System.Xml.XPath.XPathException”类型的未处理异常
附加信息:表达式的计算结果必须为 node-set

【问题讨论】:

  • //Name[./following::Type="Borrower"]

标签: c# xml xpath


【解决方案1】:

使用这个 XPath 表达式:

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

它会给你想要的结果

Bob Smith

【讨论】:

    【解决方案2】:

    或者试试这个:

    //Type[.="Borrower"]/parent::node()/preceding-sibling::node()//Name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-24
      • 2023-03-12
      • 1970-01-01
      • 2019-05-27
      • 2020-09-24
      • 2018-02-21
      • 2014-11-16
      • 1970-01-01
      相关资源
      最近更新 更多