首页 > 解决方案 > 如何使用 XSLT 转换和修改(!)嵌套标签?

问题描述

以这个 XML 为例...

<list>
  <header>
    something
  </header>
  <main>
    <p>
      (1) nothing <b>special</b> at all.
    </p>
    <p>
      (1a) and <b>another</b> thing.
    </p>
  </main>
</list>

应该改成...

<list>
  <header>
    something
  </header>
  <aside>
    <para nr="(1)">
      nothing <u>special</u> at all.
    </para>
    <para nr="(1a)">
      and <u>another</u> thing.
    </para>
  </aside>
</list>

这个 Stackoverflow 答案是我的出发点......

目前我没有真正的方法来解决这个问题。我不想引用我以前的失败...

标签: xsltnestedtransformationxpath-1.0

解决方案


我不记得回答过那个引用的问题,但我给出的答案是采取的方法。你只需要实现一个数字规则......

  1. 转换mainaside
  2. 对于每个标签,根据第一个子文本元素中括号中的值向新创建的标签p添加属性nrpara
  3. 将元素b下的标签转换pu

第二个有点棘手,但可以使用这个模板来实现,它利用一些字符串操作来提取括号中的数字

<xsl:template match="p">
    <para nr="{substring-before(substring-after(text()[1], '('), ')')}">
        <xsl:apply-templates select="@*|node()"/>
    </para>
</xsl:template>

(还要注意使用属性值模板来创建属性)

您还需要一个关联的模板来从第一个文本节点中删除数字

<xsl:template match="p/text()[1]">
    <xsl:value-of select="substring-after(., ')')" />
</xsl:template>

不过转换bu要容易得多(这是假设只有需要更改的b元素)。p

<xsl:template match="p/b">
    <u>
        <xsl:apply-templates select="@*|node()"/>
    </u>
</xsl:template>

将有一个类似的模板更改mainaside

试试这个 XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" />

    <!-- This is the Identity Transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="main">
        <aside>
            <xsl:apply-templates select="@*|node()"/>
        </aside>
    </xsl:template>

    <xsl:template match="p">
        <para nr="{substring-before(substring-after(text()[1], '('), ')')}">
            <xsl:apply-templates select="@*|node()"/>
        </para>
    </xsl:template>

    <xsl:template match="p/text()[1]">
        <xsl:value-of select="substring-after(., ')')" />
    </xsl:template>

    <xsl:template match="p/b">
        <u>
            <xsl:apply-templates select="@*|node()"/>
        </u>
    </xsl:template>
</xsl:stylesheet>

推荐阅读