macnur
macnur

Reputation: 3

Put element attribute into element of sub element

I'm currently working on restructuring of XML. Here my xml sample:

<SECTION SectionID = "S">
    <DATA>
        <ITEM ID="GLOBAL_DOCSTATUS_1000">
        <D>template</D>
        <E>template</E>
        <R>шаблон</R>
        <K>шаблон</K>
        </ITEM>
    </DATA>
</SECTION>

I need to put an attribute @SectionID as an element inside of the <ITEM> tag as a new <SECTIONID> tag with its data.

The result should look like this:

<SECTION>
  <DATA>
    <ITEM ID="GLOBAL_DOCSTATUS_1000">
    <D>template</D>
    <E>template</E>
    <R>шаблон</R>
    <K>шаблон</K>
        <SECTIONID>S</SECTIONID> 
    </ITEM>
  </DATA>
</SECTION>

Upvotes: 0

Views: 51

Answers (1)

Sean B. Durkin
Sean B. Durkin

Reputation: 12729

<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()">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="SECTION">
  <xsl:copy>
   <xsl:apply-templates select="@*[name()!='SectionID']|node()"/>
  </xsl:copy>
</xsl:template>

  <xsl:template match="SECTION[@SectionID]/DATA/ITEM">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
   <SECTIONID><xsl:value-of select="../../@SectionID" /></SECTIONID> 
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions