XPath find all elements with specific child node

前端 未结 2 1223
南笙
南笙 2020-12-04 16:25

Could you please help me to find all the elements b which have the child element c in the example below?


    
             


        
2条回答
  •  佛祖请我去吃肉
    2020-12-04 17:19

    Whenever the structure of the XML document is known, it is better to avoid using the // XPath pseudo-operator, as its use can result in big inefficiency (traversal of the whole document tree).

    Therefore, I recomment this XPath expression for the provided XML document:

    /*/b[c]
    

    This selects any b element that is a child of the top element of the XML document and that has a child-element named c.

    UPDATE: The OP asked a second question just minutes ago:

    The second question is I want to combine 2 conditions: I want to get the element which have name = "b2" and has the element c But this syntax seems not to work: //b[@name='b2' and c]

    The provided XPath expression does select exactly the wanted element.

    Here is XSLT - based verification:

    
     
     
    
     
         
     
    
    

    When this transformation is applied on the provided XML document:

    
        
        
        
    
    

    the XPath expression is evaluated and the correctly-selected element is copied to the output:

    
       
    
    

提交回复
热议问题