XSLT字符串操作

时间:2011-09-21 09:17:48

标签: xslt-2.0

有人可以告诉我下面修复最简单的方法吗?我目前有一个文件,包含多种方式来定义交叉引用(基本上链接到其他页面),我想将其中的2个转换为单个格式。 XML下面是一个显示源格式的简化示例:

<Paras>
<Para tag="CorrectTag">
<local xml:lang="en">Look at this section  <XRef XRefType="(page xx)">(page 36)</XRef> for more information</local>
</Para>
<Para tag="InCorrectTag">
<local xml:lang="en">Look at some other section (page <XRef XRefType="xx">52</XRef>) for more information</local>
</Para>
</Paras>

我想要实现的目标如下:

<Paras>
<Para tag="CorrectTag">
    <local xml:lang="en">Look at this section <XRef XRefType="(page xx)" XRefPage="36"/> for more information</local>
</Para>
<Para tag="InCorrectTag">
    <local xml:lang="en">Look at some other section <XRef XRefType="(page xx)" XRefPage="52"/> for more information</local>
</Para>
</Paras>

使用下面的xslt转换[XRef]元素

<xsl:template match="XRef">
    <xsl:copy>
        <xsl:attribute name="XRefType">(page xx)</xsl:attribute>
        <xsl:choose>
            <xsl:when test="@XRefType='(page xx)'">
                <xsl:attribute name="XRefPage" select="substring-before(substring-after(.,'(page '),')')"/>
            </xsl:when>
            <xsl:when test="@XRefType='xx'">
                <xsl:attribute name="XRefPage" select="."/>
            </xsl:when>
        </xsl:choose>
    </xsl:copy>
</xsl:template>

已经给了我这个输出:

<Paras>
<Para tag="CorrectTag">
    <local xml:lang="en">Look at this section<XRef XRefType="(page xx)" XRefPage="36"/>for more information</local>
</Para>
<Para tag="InCorrectTag">
    <local xml:lang="en">Look at some other section (page<XRef XRefType="(page xx)" XRefPage="52"/>) for more information</local>
</Para>
</Paras>

哪个已经解决了我的大部分问题但我仍然坚持如何在不删除太多其他内容的情况下清理其余的[local]元素。

我需要的是:如果字符串“(page”后跟一个XRef元素,则删除它。如果字符串“)”前面有一个XRef元素,则将其删除。否则,请勿触摸它们。

关于如何解决这个问题的任何建议?

谢谢你提前!

1 个答案:

答案 0 :(得分:1)

您应该能够使用模板解决这个问题,例如

<xsl:template match="text()[ends-with(., '(page ')][following-sibling::node()[1][self::XRef]]">
  <xsl:value-of select="replace(., '(page $', '')"/>
</xsl:template>

<xsl:template match="text()[starts-with(., ')')][preceding-sibling::node[1][self::XRef]">
  <xsl:value-of select="substring(., 2)"/>
</xsl:template>

当然,您需要确保这些文本节点的父元素的任何模板都使用apply-templates来处理子节点。