Besides Dimitre's excellent answer, this stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()[1]|@*"/>
</xsl:copy>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="Tag">
<Tag>
<Childlist>
<xsl:apply-templates select="node()[1]"/>
</Childlist>
</Tag>
</xsl:template>
<xsl:template match="*/Dlist[1]">
<xsl:copy>
<xsl:call-template name="makeItem"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Childlist|Dlist" name="makeItem">
<Item>
<xsl:apply-templates select="node()[1]"/>
</Item>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
</xsl:stylesheet>
Output:
<Root>
<Tag>
<Childlist>
<Item>
<I>1</I>
<Dlist>
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
</Dlist>
</Item>
<Item>
<I>11</I>
<Dlist>
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
</Dlist>
</Item>
</Childlist>
</Tag>
</Root>
Edit: With this input:
<Root>
<Tag>
<Childlist>
<I>1</I>
<Dlist>2</Dlist>
<Dlist>3</Dlist>
<Dlist>4</Dlist>
<F>1</F>
</Childlist>
<Childlist>
<I>11</I>
<Dlist>2</Dlist>
<Dlist>3</Dlist>
<Dlist>4</Dlist>
<F>11</F>
</Childlist>
</Tag>
</Root>
This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()[1]|@*"/>
</xsl:copy>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="Tag">
<Tag>
<Childlist>
<xsl:apply-templates select="node()[1]"/>
</Childlist>
</Tag>
</xsl:template>
<xsl:template match="*/Dlist[last()]" name="makeItem">
<Item>
<xsl:apply-templates select="node()[1]"/>
</Item>
</xsl:template>
<xsl:template match="*/Dlist[1]">
<xsl:copy>
<xsl:call-template name="wrap"/>
</xsl:copy>
<xsl:apply-templates select="following-sibling::node()
[not(self::Dlist)][1]"/>
</xsl:template>
<xsl:template match="Childlist|Dlist" name="wrap">
<xsl:call-template name="makeItem"/>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
</xsl:stylesheet>
Output:
<Root>
<Tag>
<Childlist>
<Item>
<I>1</I>
<Dlist>
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
</Dlist>
<F>1</F>
</Item>
<Item>
<I>11</I>
<Dlist>
<Item>2</Item>
<Item>3</Item>
<Item>4</Item>
</Dlist>
<F>11</F>
</Item>
</Childlist>
</Tag>
</Root>
Note: This assumes Dlist
elements are all next siblings. So Dlist[1]
opens the new level and after that apply templates to next no Dlist
node, and Dlist[last()]
close the level not applying templates to next sibling.