代码之家  ›  专栏  ›  技术社区  ›  sergionni

XPath:返回具有特定属性的第一个符合条件的子项

  •  0
  • sergionni  · 技术社区  · 12 年前

    具有以下层次结构:

    Parent1
        --> child1(@name = 'abc')
        --> child2(@name = 'xyz')
        --> child3(@name = 'qqq')
    
    Parent2
        --> child1
        --> child2(@name = 'yui')
    

    XPath路径 其返回所需的以下节点:

    child1 from Parent1

    child2 from Parent2

    规则如下:
    回来 首次发生 小孩 只有 在这种情况下具有特定属性 @name

    注意:
    first() [1] 不起作用

    1 回复  |  直到 12 年前
        1
  •  1
  •   Jasper    12 年前

    以下xpath:

    /root/node()/node()[@name][position()=1]
    

    使用此XML:

    <?xml version="1.0" encoding="utf-8"?>
    <root>
      <parent1>
        <child1 name="abc"></child1>
        <child2 name="xyz"></child2>
        <child3 name="qqq"></child3>
      </parent1>
      <parent2>
        <child1></child1>
        <child2 name="yui"></child2>
      </parent2>
    </root>
    

    退货:

    Element='<child1 name="abc" />'
    Element='<child2 name="yui" />'