【问题标题】:Format output in XSLT according to content根据内容在 XSLT 中格式化输出
【发布时间】:2017-05-26 14:59:22
【问题描述】:

有这个 xml sn-p:

<paragraph><bold>Test</bold> - This <italic>word</italic> should be <underline>underlined</underline> according to xml</paragraph>

如何在将使用过的标签替换为 HTML 中使用的标签时将此“段落”输出到 HTML 中?

我试过这个 XSLT sn-p 但它不会打印嵌套标签之外的文本,只打印粗体、斜体和下划线之间的文本。

<xsl:template match="p:paragraph">
                <xsl:for-each select="./*">
                    <xsl:choose>
                        <xsl:when test="name(.)='bold'">
                            <xsl:apply-templates select="."/>
                        </xsl:when>
                        <xsl:when test="name(.)='italic'">
                            <xsl:apply-templates select="."/>
                        </xsl:when>
                        <xsl:when test="name(.)='underlined'">
                            <xsl:apply-templates select="."/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:value-of select="./text()"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:for-each>
</xsl:template>

<xsl:template match="bold">
    <p><b><xsl:value-of select="current()"/></b></p>
</xsl:template>

<xsl:template match="italic">
    <p><i><xsl:value-of select="current()"/></i></p>
</xsl:template>

<xsl:template match="underline">
    <p><u><xsl:value-of select="current()"/></u></p>
</xsl:template>

我怎样才能使模板按预期输出?

提前致谢

【问题讨论】:

    标签: html xml xslt


    【解决方案1】:

    您的主要问题是./*(可以简化为仅*)仅选择元素,但您也想选择文本节点。所以你能做的就是把它改成这样......

    <xsl:for-each select="node()">
    

    您还需要将xsl:otherwise 更改为此...

    <xsl:otherwise>
        <xsl:value-of select="."/>
    </xsl:otherwise>
    

    但是,您可以简化整个 XSLT 以更好地使用模板匹配。试试这个 XSLT

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
        <xsl:output method="html" indent="yes" />
    
        <xsl:template match="paragraph">
            <p>
                <xsl:apply-templates />
            </p>
        </xsl:template>
    
        <xsl:template match="bold">
            <b>
               <xsl:apply-templates /> 
            </b>
        </xsl:template>
    
        <xsl:template match="italic">
            <i>
               <xsl:apply-templates /> 
            </i>
        </xsl:template>
    
        <xsl:template match="underline">
            <u>
               <xsl:apply-templates /> 
            </u>
        </xsl:template>
    
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    

    (您显然需要调整它以处理名称空间,因为您当前的 XSLT 选择 p:paragraph,这表明您的 XML 中有名称空间)。

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      相关资源
      最近更新 更多