Move specific child nodes to a new grandson level

I found other questions about moving nodes up to the parent, but I don’t have enough trick to move them to the newly created node.

Given:

<Villain>
  <Name>Dr Evil</Name>
  <Age>49</Age>
  <Like>Money</Like>
  <Like>Sharks</Like>
  <Like>Lasers</Like>
</Villain>

I am trying to convert this using XSLT to:

<Villain>
  <Name>Dr Evil</Name>
  <Age>49</Age>
  <Likes>
    <Like>Money</Like>
    <Like>Sharks</Like>
    <Like>Lasers</Like>
  </Likes>
</Villain>

In other words, insert a new child node and move all the child nodes under it like “.”

+3
source share
1 answer

This conversion is :

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*" name="identity">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

  <xsl:template match="Like[1]">
   <Likes>
    <xsl:apply-templates select="../Like" mode="copy"/>
   </Likes>
  </xsl:template>

   <xsl:template match="*" mode="copy">
    <xsl:call-template name="identity"/>
   </xsl:template>
   <xsl:template match="Like"/>
 </xsl:stylesheet>

when applied to the provided XML document :

<Villain>
  <Name>Dr Evil</Name>
  <Age>49</Age>
  <Like>Money</Like>
  <Like>Sharks</Like>
  <Like>Lasers</Like>
</Villain>

creates the desired, correct result :

<Villain>
   <Name>Dr Evil</Name>
   <Age>49</Age>
   <Likes>
      <Like>Money</Like>
      <Like>Sharks</Like>
      <Like>Lasers</Like>
   </Likes>
</Villain>

Please note :

  • Use and redefinition of an identification rule .

  • , .

+4

Source: https://habr.com/ru/post/1762977/


All Articles