2014-09-05 65 views
1

我需要将一些XML文件转换为略有不同的XML结构。我想保留一些元素内容并丢弃其他内容。这可能吗?我需要操纵元素的文本内容,而其他问题似乎没有这样做。 我的XML文件类似于此使用XSLT对元素的文本内容进行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

这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> 

这是否已经符合你的要求?

在文本节点中保留“视觉上美观”的缩进并不是微不足道的,但是,我想你并不真的依赖于这个。

+0

你说得对,空白并不重要。 – David 2014-09-05 16:00:10