XSLT - 仅将指定的内容移动到节点

时间:2017-11-21 06:12:49

标签: xml xslt

我的输入XML就像,

<section counter="yes" level="2">
<title>Course of Illness Following Stroke(<link idref="c003_f001">Fig. 3.1</link>)</title>
<section counter="yes" level="3">

输出应该是,

<section counter="yes" level="2">
<title>Course of Illness Following Stroke</title>
<para><link idref="c003_f001">(Fig. 3.1)</link></para>
<section counter="yes" level="3">

每当链接出现在&#39; title&#39;用括号&#39;()&#39;那么它应该转移到下一段。如果&#39; para&#39;没有出现然后我们应该创建和移动整个链接&#39;括号&#39;()&#39;。

我已经编写了XSLT,但没有给出所需的输出。

 <xsl:template match="title/text()">
    <xsl:if test="matches(., '\(') and following::node()[self::link]">
        <para>
        <xsl:copy>                        
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
        </para>
    </xsl:if>  
    <xsl:if test="matches(., '\)') and following::node()[self::link]">
        <xsl:copy>                        
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:if>  
</xsl:template>

请您指导我们解决此问题。

1 个答案:

答案 0 :(得分:1)

在与文本节点匹配的模板中使用xsl:apply-templates没有多大意义。 (另一个问题:你并不需要matches(),因为你不需要正则表达式来搜索单个圆括号;相反,contains()就足够了。)

您的方案的过程可能如下所示:查找title包含link括号括起来的*-sibling::substring-*()title组合。你可以用XPath完全做到这一点。在匹配元素中,您只需重新组合标题,从复制(开始,并在link之前填入所有文本。可能需要对此进行调整,具体取决于标题的可能内容:也许它可以包含link之前的其他元素(如果是这种情况,请告诉我们)。之后,只需将para的副本插入<xsl:template match="title[link[ends-with(preceding-sibling::text(), '(') and starts-with(following-sibling::text(), ')')]]"> <xsl:copy> <xsl:value-of select="substring-before(text()[1], '(')"/> </xsl:copy> <para> <!-- edit --> <!--<xsl:copy-of select="link"/>--> <xsl:apply-templates mode="parenthesize" select="link"/> <!-- end edit --> </para> </xsl:template> <!-- edit: new template --> <xsl:template match="link" mode="parenthesize"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:text>(</xsl:text> <xsl:apply-templates/> <xsl:text>)</xsl:text> </xsl:copy> </xsl:template> 即可。就是这样。

Sheet1

PS。我假设您对所有其他元素使用标识变换。