【问题标题】:Using Java to find Nested XPATH references使用 Java 查找嵌套的 XPATH 引用
【发布时间】:2021-08-05 22:50:45
【问题描述】:

我有一个示例 XML,如下所示。

<cars>
   <car id="001">
    <name>FirstCar</name>
    <relationships>
      <relationship type="Owned By">Mike</relationship>
    <relationships>
   </car>
   <car id="002">
    <name>SecondCar</name>
    <relationships>
      <relationship type="Owned By">Jake</relationship>
    <relationships>
   </car>
   <car id="003">
   <name>ThirdCar</name>
    <relationships>
      <relationship type="Leased By">Jason</relationship>
    <relationships>
   </car>
</cars>

我正在尝试使用 Java 创建一个 XPath 查询,其中列出了所有拥有车主的汽车的 ID。我已经尝试了下面的 2 个 xpath 表达式,但它们都返回 null:

xpathExpression = "/cars/car/relationships/relationship[@type='Owned By']/@id";
xpathExpression = "/cars[./relationships/relationship[@type='Owned By']]/@id";

我还可以使用什么作为 xpath 表达式来列出所有拥有汽车的 ID?

【问题讨论】:

  • 顺便说一句,xml 示例是无效的 xml。

标签: java xml xcode xpath


【解决方案1】:

简单使用

/cars/car/relationships/relationship[@type='Owned By']/../../@id

【讨论】:

    【解决方案2】:

    这些 xpath 将根据请求查找属性

    //car[relationships/relationship[@type="Owned By"]]/@id
    //relationship[@type="Owned By"]/ancestor::car/@id
    

    【讨论】:

      【解决方案3】:

      我觉得最直接的就是

      //car[relationships/relationship/@type="Owned By"]/@id
      

      但您已经获得了其他在技术上同样正确的选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多