首先,您的 XML 格式不正确,因为属性应该用撇号或引号括起来,但我猜这可能是一个简单的错字。
至于具体问题是一个处理指令,所以你的xsl:if检查 text() 不会选择这个。
您还遇到了一个问题,<xsl:value-of select="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。