Xpath error with not() and ends-with()

前端 未结 4 1909
时光说笑
时光说笑 2021-01-05 11:58

I have the following Xpath expression:

//*[not(input)][ends-with(@*, \'Copyright\')]

I expect it to give me all elements - except input - w

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 12:20

    I have the following Xpath expression:

    //*[not(input)][ends-with(@*, 'Copyright')]
    

    I expect it to give me all elements - except input - with any attribute value which ends with "Copyright".

    There are a few issues here:

    1. ends-with() is a standard XPath 2.0 function only, so the chances are you are using an XPath 1.0 engine and it correctly raises an error because it doesn't know about a function called ends-with().

    2. Even if you are working with an XPath 2.0 processor, the expression ends-with(@*, 'Copyright') results in error in the general case, because the ends-with() function is defined to accept atmost a single string (xs:string?) as both of its operands -- however @* produces a sequence of more than one string in the case when the element has more than one attribute.

    3. //*[not(input)] doesn't mean "select all elements that are not named input. The real meaning is: "Select all elements that dont have a child element named "input".

    Solution:

    1. Use this XPath 2.0 expression: //*[not(self::input)][@*[ends-with(.,'Copyright')]]

    2. In the case of XPath 1.0 use this expression:

    ....

      //*[not(self::input)]
            [@*[substring(., string-length() -8) = 'Copyright']]
    

    Here is a short and complete verification of the last XPath expression, using XSLT:

    
     
     
    
     
         
     
    
    

    when this transformation is applied on the following XML document:

    
     
     
     
    
    

    the wanted, correct result is produced:

    
    

    In the case of the XML document being in a default namespace:

    
     
     
    
     
         
     
    
    

    when applied on this XML document:

    
     
     
     
    
    

    the wanted, correct result is produced:

    
    

提交回复
热议问题