代码之家  ›  专栏  ›  技术社区  ›  Ryan Stille

XPath是否只能返回子节点为X的节点?

  •  32
  • Ryan Stille  · 技术社区  · 16 年前

    lizard pig

    <pets>
      <cat>
        <foo>don't care about this</foo>
      </cat>
      <dog>
       <foo>not this one either</foo>
      </dog>
      <lizard>
       <bar>lizard should be returned, because it has a child of bar</bar>
      </lizard>
      <pig>
       <bar>return pig, too</bar>
      </pig>
    </pets>
    

    这个Xpath给了我所有的宠物: "/pets/*" ,但我只想要具有名称的子节点的宠物 'bar' .

    3 回复  |  直到 7 年前
        1
  •  55
  •   rogerdpack    9 年前

    它在这里,在它所有的荣耀

    /pets/*[bar]
    

    L1:给我所有的孩子 pets 有孩子的人 bar

        2
  •  26
  •   Paul D. Waite    13 年前
    /pets/child::*[child::bar]
    

    但在这种情况下,我宁愿使用 descendant::

    /pets[descendant::bar]
    
        3
  •  5
  •   Hirnhamster    10 年前

    <pets>
        <cat>
            <foo>don't care about this</foo>
        </cat>
        <dog>
            <foo>not this one either</foo>
        </dog>
        <lizard>
            <bar att="baz">lizard should be returned, because it has a child of bar</bar>
        </lizard>
        <pig>
            <bar>don't return pig - it has no att=bar </bar>
        </pig>
    </pets>
    

    现在,你只关心一切 pets 有孩子吗 bar 它有一个属性 att 有价值 baz . 可以使用以下xpath表达式:

    //pets/*[descendant::bar[@att='baz']]
    

    <lizard>
        <bar att="baz">lizard should be returned, because it has a child of bar</bar>
    </lizard>