元素的XML操作'使用XSLT的文本内容

时间:2014-09-05 14:40:07

标签: xml xslt

我需要将许多XML文件转换为略有不同的XML结构。我想保留一些元素内容并丢弃其他内容。这可能吗?我需要操纵元素的文本内容,而其他问题似乎并没有这样做。 我的XML文件与此类似

<root>
    <a>
        <b>
            BBB1
            <c>CCCC</c>
            BBB2
            <e>
                DDDD1
                <f>EEEE</f>
                DDDD2
            </e>
            BBB3
        </b>
    </a>
</root>

我希望输出为

<root>
    <a>
        <b>
            CCCC
            <e>
                DDDD1
                EEEE
                DDDD2
            </e>
        </b>
    </a>
</root>

我的XSL骨架如下所示:

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

<xsl:template match="f">
    <xsl:value-of select="f"/>
</xsl:template>

<xsl:template match="/"> 
<root>
    <a>
        <xsl:for-each select="a/b">
            <b>
                <c>
                    <xsl:value-of select="c"/>
                </c>
                <e>
                    <xsl:apply-templates/>
                    <xsl:value-of select="e"/>
                </e>
            </b>
        </xsl:for-each>
    </a>
</root>
</xsl:template>

1 个答案:

答案 0 :(得分:1)

此XSLT 1.0样式表

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- copy everything as-is ... -->
  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
  </xsl:template>

  <!-- ...except for <c> and <f> elements, output their values only -->
  <xsl:template match="c | f">
    <xsl:value-of select="." />
  </xsl:template>

  <!-- ...and don't output direct text children from <b> elements -->
  <xsl:template match="b/text()" />

</xsl:stylesheet>

给你

<root>
    <a>
        <b>CCCC<e>
                DDDD1
                EEEE
                DDDD2
            </e></b>
    </a>
</root>

这是否符合您的要求?

在文本节点中保持“光学上好”的缩进并非易事,但是,我认为你并不真正依赖它。