我有以下Xpath表达式:
//*[not(input)][ends-with(@*, 'Copyright')]我希望它能给我所有元素(输入除外),并带有以“版权”结尾的任何属性值。
这里有一些问题 :
ends-with()
仅是标准的XPath 2.0函数,因此您可能正在使用XPath 1.0引擎,并且由于它不知道称为的函数,因此它会正确引发错误ends-with()
。即使您使用的是XPath 2.0处理器,
ends-with(@*, 'Copyright')
在一般情况下该表达式也会导致错误,因为该ends-with()
函数被定义为最多接受单个字符串(xs:string?
)作为其两个操作数-但是@*
会产生一个以上字符串的序列在元素具有多个属性的情况下。//*[not(input)]
并不是说“选择所有未命名的元素input
。真正的含义是:”选择没有子元素“ input”的所有元素。
解决方案 :
使用此XPath 2.0表达式:
//*[not(self::input)][@*[ends-with(.,'Copyright')]]
对于XPath 1.0,请使用以下表达式:
....
//*[not(self::input)] [@*[substring(., string-length() -8) = 'Copyright']]
这是使用XSLT对最后一个XPath表达式进行的简短完整的验证:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/*"> <xsl:copy-of select= "//*[not(self::input)][@*[substring(., string-length() -8) = 'Copyright' ] ]"/> </xsl:template></xsl:stylesheet>
当此转换应用于以下XML文档时:
<html> <input/> <a x="Copyright not"/> <a y="This is a Copyright"/></html>
产生想要的正确结果 :
<a y="This is a Copyright"/>
如果XML文档位于默认名称空间中 :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://www.w3.org/1999/xhtml" > <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/*"> <xsl:copy-of select= "//*[not(self::x:input)][@*[substring(., string-length() -8) = 'Copyright' ] ]"/> </xsl:template></xsl:stylesheet>
当应用于此XML文档时 :
<html xmlns="http://www.w3.org/1999/xhtml"> <input z="This is a Copyright"/> <a x="Copyright not"/> <a y="This is a Copyright"/></html>
所需的正确结果产生了:
<a xmlns="http://www.w3.org/1999/xhtml" y="This is a Copyright"/>



