在XSL转换中,我得到了一个相当长的XPath(大约20个不同节点的并集)。因为这个路径经常需要,所以它的缩写会很好。
缩写必须以在当前上下文中进行评估的方式制作,因此使用全局变量或其他东西是行不通的。
目标版本是带有EXSLT扩展的XSLT1.0。
谢谢,
Jost
如果不能有全局变量,那么函数可能是解决方案。
您可以使用实体来提供冗长XPath的缩写。
XSLT是一个XML文件,因此XML实体可以在XSLT中的任何位置使用。实体将在解析XSLT时进行扩展和解析。
您可以对实体执行某些操作,而不能对全局XSLT变量执行这些操作,即在XPath和匹配表达式中使用实体。
例如,您可以为长XPath语句创建一个实体,并在多个位置重用它,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE stylesheet [
<!ENTITY lengthyXPath "elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20">
]>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes"/>
<xsl:template match="/">
<output>
<xsl:apply-templates select="/*/*"/>
</output>
</xsl:template>
<xsl:template match="foo">
<xsl:comment>mached foo child elements from: &lengthyXPath;</xsl:comment>
<xsl:apply-templates select="&lengthyXPath;"/>
</xsl:template>
<xsl:template match="bar">
<xsl:comment>mached bar child elements from: &lengthyXPath;</xsl:comment>
<xsl:apply-templates select="&lengthyXPath;"/>
</xsl:template>
<xsl:template match="baz">
<xsl:comment>mached baz child elements from: &lengthyXPath;</xsl:comment>
<xsl:apply-templates select="&lengthyXPath;"/>
</xsl:template>
<xsl:template match="&lengthyXPath;">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
应用于此XML:时
<doc>
<foo>
<elem>no match</elem>
<elem1>1</elem1>
<elem>no match</elem>
<elem3>3</elem3>
<elem>no match</elem>
<elem5>5</elem5>
</foo>
<bar>
<elem>no match</elem>
<elem7>7</elem7>
<elem>no match</elem>
<elem9>9</elem9>
<elem>no match</elem>
<elem10>10</elem10>
</bar>
<baz>
<elem>no match</elem>
<elem11>11</elem11>
<elem>no match</elem>
<elem13>13</elem13>
<elem>no match</elem>
<elem15>15</elem15>
</baz>
</doc>
产生以下输出:
<?xml version="1.0" encoding="UTF-8"?>
<output><!--mached foo child elements from: elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20--><elem1>1</elem1>
<elem3>3</elem3>
<elem5>5</elem5>
<!--mached bar child elements from: elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20--><elem7>7</elem7>
<elem9>9</elem9>
<elem10>10</elem10>
<!--mached baz child elements from: elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20--><elem11>11</elem11>
<elem13>13</elem13>
<elem15>15</elem15>
</output>