XSLT将子节点文本复制到父节点

时间:2017-11-03 11:09:55

标签: xml xslt xslt-1.0

我需要帮助以下xslt代码。 我输入了:

 <book>
      <book1>
           <name>abc</name>
           <revision>1</revision>
      </book1>
      <book2>
           <name>pqr</name>
           <author>def</author>
      </book2>
 </book>

我的预期输出为:

  <book>
      <item>
           <name>book1</name>
           <value>abc1</value>
      </item>
      <item>
           <name>book2</name>
           <value>pqrdef</value>
      </item>
 </book>

我尝试使用* / text()获取值节点的值,但我只从第一个子节点获取文本。将来我会有很多这样的儿童元素。

提前致谢。

此致 Minakshi

1 个答案:

答案 0 :(得分:0)

此样式表将为您提供所需内容。即使boonK元素的子元素增加,模板也不需要更改。

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

    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:template match="book">
        <xsl:copy>
            <xsl:apply-templates select="*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="book/*">
        <item>
            <name>
                <xsl:value-of select="name()"/>
            </name>
            <value>
                <xsl:for-each select="*">
                    <xsl:value-of select="."/>
                </xsl:for-each>
            </value>
        </item>
    </xsl:template>

</xsl:stylesheet>