xml - 从单个节点中的属性构建 XML 结构

标签 xml xslt xslt-2.0

我有以下 XML 源:

<element not-relevant="true" bold="true" superscript="true" subscript="false" text="stuff"/>

以任何顺序,我需要遍历特定属性(即仅与我正在构建的 HTML 相关的属性:粗体/上标/下标等),并且这些属性之一的计算结果为“真”,输出嵌套元素得到如下输出:

<strong>
    <sup>
        stuff
    </sup>
</strong>

我觉得我需要使用某种递归,如下所示(当然没有无限循环):

<xsl:template match="element">
    <xsl:call-template name="content">
        <xsl:with-param name="text" select="@text"/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="content">
    <xsl:param name="text"/>
    <xsl:choose>
        <xsl:when test="@bold = 'true'">
            <strong>
                <xsl:copy>
                    <xsl:call-template name="content">
                        <xsl:with-param name="text" select="$text"/>
                    </xsl:call-template>
                <xsl:copy>
            </strong>
        </xsl:when>
        <xsl:when test="@subscript = 'true'">
            <sub>
                <xsl:copy>
                    <xsl:call-template name="content">
                        <xsl:with-param name="text" select="$text"/>
                    </xsl:call-template>
                <xsl:copy>
            </sub>
        </xsl:when>
        <xsl:when test="@superscript = 'true'">
            <sup>
                <xsl:copy>
                    <xsl:call-template name="content">
                        <xsl:with-param name="text" select="$text"/>
                    </xsl:call-template>
                <xsl:copy>
            </sup>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" disable-output-escaping="yes"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

有什么想法吗?我正在寻找最干净的 XSLT 2.0 解决方案并感谢您的帮助。

谢谢,

最佳答案

这是 <xsl:next-match/> 的一个很好的用例:

<xsl:template match="element" priority="1">
  <xsl:value-of select="@text" />
</xsl:template>

<xsl:template match="element[@superscript = 'true']" priority="2">
  <sup><xsl:next-match/></sup>
</xsl:template>

<xsl:template match="element[@subscript = 'true']" priority="3">
  <sub><xsl:next-match/></sub>
</xsl:template>

<xsl:template match="element[@bold = 'true']" priority="4">
  <strong><xsl:next-match/></strong>
</xsl:template>

当您将模板应用于 element 时元素它将首先触发优先级最高的匹配模板,如果该模板使用 next-match它将委托(delegate)给下一个最高优先级,等等。你的例子element问题中的匹配上面的第一个、第二个和第四个模板,因此最初将选择“粗体”模板,然后将委托(delegate)给“上标”模板,最后委托(delegate)给通用 element一,导致<strong><sup>stuff</sup></strong> .

从这个例子中可以看出,优先级数字决定了嵌套的顺序 - 如果第二个和第四个模板的优先级颠倒,你会得到 <sup><strong>stuff</strong></sup>相反。

关于xml - 从单个节点中的属性构建 XML 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26000325/

相关文章:

需要 XML 命名空间吗?

java - SAX 解析器不工作

xslt - 在内容查询 Web 部件中添加分页

xslt-2.0 - XSLT 2.0 : Find missing elements in a sequence

java dom 搜索 xml

javascript - 将 xsl 嵌入到 XML 文件中

xslt - 选择与开头名称匹配的元素

XSLT:如何在 <xsl:copy> 期间更改属性值?

xml - XSL+XPATH : Compare previous node attribute to current node attribute

xml - 在 Coldfusion 中使用 Unicode 字符解析 XML