如何按顺序使用 XSLT 解析嵌套标签? [英] How to parse nested tags using XSLT in sequence?

查看:20
本文介绍了如何按顺序使用 XSLT 解析嵌套标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 XML 有以下场景.

I have below scenario for my XML.

<content>
  <para>text-1 <emphasis type="bold">text-2</emphasis> text-3</para>
</content>

我想像下面那样解析它

<content>
<p>text-1 <b>text-2</b> text-3</p>
</content>

我已经创建了我的 XSLT 如下

I have created my XSLT as below

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="ISO-8859-1" indent="no"/>

<xsl:template name="para">
    <p>
        <xsl:value-of select="text()" disable-output-escaping="yes"/>
        <xsl:for-each select="child::*">
            <xsl:if test="name()='emphasis'">
                <xsl:call-template name="emphasis"/>
            </xsl:if>
        </xsl:for-each>

    </p>
</xsl:template>
<xsl:template name="emphasis">
    <xsl:if test="attribute::type = 'bold'">
        <b>
            <xsl:value-of select="text()" disable-output-escaping="yes"/>
        </b>
    </xsl:if>
</xsl:template>

<xsl:template match="/">
    <content>
        <xsl:for-each select="content/child::*">
            <xsl:if test="name()='para'">
                <xsl:call-template name="para"/>
            </xsl:if>
        </xsl:for-each>
    </content>
</xsl:template>
</xsl:stylesheet>

上面提供的 XSLT 生成如下输出

XSLT provided above is generating output like below

<content>
 <p>text-1  text-3<b>text-2 </b></p>
</content>

请用你的建议指导我,我怎样才能得到我想要的输出?

Please guide me with your suggestions, how can I get my desire output?

推荐答案

这样做 ;)

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>

    <xsl:template match="content">
        <content><xsl:apply-templates select="para" /></content>
    </xsl:template>

    <xsl:template match="emphasis [@type='bold']">
        <b><xsl:value-of select="." /></b>
    </xsl:template>

</xsl:stylesheet>

当你这样做时,默认模板将捕获 text-1 和 text-3

when you do it like this the default template will catch text-1 and text-3

这篇关于如何按顺序使用 XSLT 解析嵌套标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆