首先,您的 XML 格式不正确,因为属性应该用撇号或引号括起来,但我猜这可能是一个简单的错字。
至于具体问题是处理指令,因此您检查 text() 的 xsl:if 不会选择它。
你在<xsl:value-of select="link" /> 处也遇到了问题,因为你当前的上下文已经在 link 元素上,所以它正在寻找另一个 link 元素那是当前的孩子。你可能只想做这样的事情
<xsl:value-of select="." />
所以,你可以像这样重写你的模板
<xsl:template match="link">
<xsl:element name="{local-name(.)}">
<xsl:attribute name="sshref">
<xsl:value-of select="@ref"/>
</xsl:attribute>
<xsl:if test="text()|processing-instruction()">
<xsl:element name="num">
<xsl:apply-templates select="text()|processing-instruction()"/>
</xsl:element>
</xsl:if>
</xsl:element>
</xsl:template>
<xsl:template match="processing-instruction()">
<xsl:value-of select="."/>
</xsl:template>
然而,值得注意的是,通常最好避免使用 xsl:if 元素,而使用模板匹配的强大功能。试试这个替代的 XSLT。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="link[text()|processing-instruction()]">
<link>
<num>
<xsl:apply-templates select="text()|processing-instruction()"/>
</num>
</link>
</xsl:template>
<xsl:template match="link/@ref">
<xsl:attribute name="ssref">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<xsl:template match="processing-instruction()">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="@*|node()[not(self::processing-instruction())]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
应用于以下 XMK 时
<comp>
<link ref="1">1997</link>
<link ref="2"><?LINK 2008?></link>
</comp>
以下是输出:
<comp>
<link sshref="1">
<num>1997</num>
</link>
<link sshref="2">
<num>2008</num>
</link>
</comp>
请注意,除非您想要动态命名的元素,否则无需使用 xsl:element。