<xsl:template match="//foo[1]">
匹配多个元素(所有<foo>
没有先前<foo>
同级的元素)
<xsl:template match="(//foo)[1]">
是一个错误。
如何仅在文档中第一次出现元素时进行匹配?
这是输入文档的示例:
<test>
<foo>1</foo>
<another>
<foo>2</foo>
</another>
<more>
<bar>3</bar>
<foo>4</foo>
</more>
<something>
<foo>5</foo>
<bar>6</bar>
<foo>7</foo>
</something>
<final>
<hum>8</hum>
<foo>9</foo>
<foo>10</foo>
</final>
</test>
我的意图是使匹配foo
文本,1
而不要匹配其他文本。假定foo
可以在文档中的任何地方发生。
为了仅匹配foo
文档中的第一个匹配项,您必须检查既没有前面的foo
元素又没有foo
祖先:
<xsl:template match="foo[not(preceding::foo or ancestor::foo)]">
考虑以下样本输入XML:
<r>
<a/>
<foo>
<b/>
<foo/>
</foo>
<foo>
<foo/>
</foo>
<c/>
</r>
这个XSLT,
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="foo[not(preceding::foo or ancestor::foo)]">
<FirstFoo>
<xsl:apply-templates/>
</FirstFoo>
</xsl:template>
<xsl:template match="foo">
<LaterFoo>
<xsl:apply-templates/>
</LaterFoo>
</xsl:template>
</xsl:stylesheet>
将输出此XML,
<?xml version="1.0" encoding="UTF-8"?>
<r>
<a/>
<FirstFoo>
<b/>
<LaterFoo/>
</FirstFoo>
<LaterFoo>
<LaterFoo/>
</LaterFoo>
<c/>
</r>
但是,如果仅检查前一个轴,则将输出以下XML:
<?xml version="1.0" encoding="UTF-8"?>
<r>
<a/>
<FirstFoo>
<b/>
<FirstFoo/>
</FirstFoo>
<LaterFoo>
<LaterFoo/>
</LaterFoo>
<c/>
</r>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句