我有一个xml文档,我试图用xsl样式。问题取决于我需要从某个节点提取的值,但在xsl中,我不知道如何区分以下两个节点:
XML:<a number=1>
<car>1</car>
</a>
<a number=2>
<dog>1</dog>
</a>
<I_want_to_display>
<number>2</number>
</I_want_to_display>
XSL: <xsl:for-eachselect="I_want_to_display">
<xsl:if test="number==2">
....display everything in <a number=2>
</xsl:if>
不知道您想要什么输出,但这里有一个猜测。
格式良好的XML输入:
<xml>
<a number="1">
<car>1</car>
</a>
<a number="2">
<dog>1</dog>
</a>
<I_want_to_display>
<number>2</number>
</I_want_to_display>
</xml>
:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:apply-templates select="node()|@*"/>
</xsl:template>
<xsl:template match="I_want_to_display">
<xsl:variable name="vNbr" select="number/text()"/>
<xsl:copy-of select="//*[normalize-space(@number) = $vNbr]"/>
</xsl:template>
</xsl:stylesheet>
产生如下输出:
<a number="2">
<dog>1</dog>
</a>
使用这个XPath俏皮话:
/*/*[@number = /*/I_want_to_display/number]
完整的XSLT代码(9行):
<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="/*/*[@number = /*/I_want_to_display/number]"/>
</xsl:template>
</xsl:stylesheet>
当对以下XML文档应用此转换时(因为没有提供格式良好的XML文档!):
<t>
<a number="1">
<car>1</car>
</a>
<a number="2">
<dog>1</dog>
</a>
<I_want_to_display>
<number>2</number>
</I_want_to_display>
</t>
生成所需的正确结果:
<a number="2">
<dog>1</dog>
</a>
说明:对于具有相同字符串值的每一对节点(一个来自第一个节点集,另一个来自第二个节点集),XPath运算符=
应用于两个节点集时为true()
。
<xsl:for-each select="I_want_to_display">
<xsl:copy-of select="preceding-sibling::a[@number = current()/number]/node()>
</xsl:for-each>
您可以使用key:
收集a
节点。<xsl:key name="ka" match="a" use="@number"/>
,并使用键稍后在所需的模板中引用它们,如:
<xsl:for-each select="I_want_to_display">
<xsl:copy-of select="key('ka',normalize-space(number))"/>
</xsl:for-each>