簡単な条件を追加することで、処理命令に親要素があるかどうかを確認できます
<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>