您可以通过添加一个简单的条件来检查处理指令是否有父元素
<xsl:template match="processing-instruction('Pub')[parent::*]">
但要小心,如果您的 XML 看起来像这样:
<div>
<?Pub _kern Amount="-25pt"?>
</div>
如果首先匹配并复制了空白文本节点,您仍然可能会收到错误消息。您可能需要xsl:strip-space
在 XSLT 中包含该命令。
例如,这会出错
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="processing-instruction('Pub')[parent::*]">
<xsl:choose>
<xsl:when test="starts-with(., '_kern')">
<xsl:attribute name="style"><xsl:text>padding-left: </xsl:text>
<xsl:value-of select="if (contains(.,'Amount')) then (substring-before(substring-after(., 'Amount="'), '"')) else '12pt'"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
但这并不......
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:strip-space elements="*" />
<xsl:template match="processing-instruction('Pub')[parent::*]">
<xsl:choose>
<xsl:when test="starts-with(., '_kern')">
<xsl:attribute name="style"><xsl:text>padding-left: </xsl:text>
<xsl:value-of select="if (contains(.,'Amount')) then (substring-before(substring-after(., 'Amount="'), '"')) else '12pt'"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
编辑:响应您的评论,xsl:strip-space
如果在处理指令之前有一个先前的兄弟姐妹,即使您仍然会收到错误
<div>
<text></text>
<?Pub _kern Amount="-25pt"?>
</div>
这是因为如果父元素已经有子节点输出,则无法将属性添加到父元素。
如果打算尝试将属性添加到父级,但如果不创建跨度标记,则可以将匹配处理指令的模板格式更改为:
<xsl:template match="processing-instruction('Pub')">
<xsl:choose>
<xsl:when test="not(parent::*) or preceding-sibling::node()">
<span>
<!-- Add attribute -->
</span>
</xsl:when>
<xsl:otherwise>
<!-- Add attribute -->
</xsl:otherwise>
</xsl:choose>
</xsl:template>
并且属性的添加可以在模板中完成,避免重复编码。试试这个 XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:strip-space elements="*" />
<xsl:template match="processing-instruction('Pub')">
<xsl:choose>
<xsl:when test="not(parent::*) or preceding-sibling::node()">
<span>
<xsl:call-template name="processing-instruction"/>
</span>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="processing-instruction"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="processing-instruction">
<xsl:choose>
<xsl:when test="starts-with(., '_kern')">
<xsl:attribute name="style"><xsl:text>padding-left: </xsl:text>
<xsl:value-of select="if (contains(.,'Amount')) then (substring-before(substring-after(., 'Amount="'), '"')) else '12pt'"/>
</xsl:attribute>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>