简体   繁体   中英

XSLT Copy child nodes text to parent node

I need help in following xslt code. I have input as:

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

My expected output as:

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

I have tried fetching value for value node using */text() but i get text only from first child. In future I have many such child elements.

Thanks in advance.

Regards, Minakshi

This stylesheet will give you what you want. Even if the child of boonK element increase, the template will not need to be change.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM