XPath query with descendant and descendant text() predicates

后端 未结 3 1605
半阙折子戏
半阙折子戏 2021-02-05 10:27

I would like to construct an XPath query that will return a \"div\" or \"table\" element, so long as it has a descendant containing the text \"abc\". The one caveat is that it

3条回答
  •  梦毁少年i
    2021-02-05 11:25

    Something different: :)

    //text()[contains(.,'abc')]/ancestor::*[self::div or self::table][1]
    

    Seems a lot shorter than the other solutions, doesn't it? :)

    Translated to simple English: For any text node in the document that contains the string "abc" select its first ancestor that is either a div or a table.

    This is more efficient, as only one full scan of the document tree (and not any other) is required, and the ancestor::* traversal is very cheap compared to a descendent:: (tree) scan.

    To verify that this solution "really works":

    
     
     
    
     
      
     
    
    

    when this transformation is performed on the provided XML document:

    abcdefg

    123456

    the wanted, correct result is produced:

    abcdefg

    Note: It isn't necessary to use XSLT -- any XPath 1.0 host -- such as DOM, must obtain the same result.

提交回复
热议问题