0

I have xml file with structure:

<root>
 <header>
  <filename>file.txt</filename>
 </header>
 <orders>
  <order>
    <name>foo bar</name>
  </order>
  <order>
    <name>foo bar</name>
  </order>
  ...
 </orders>
</root>

But i want to get rid of the tag so the result xml should look like this:

<root>
 <header>
  <filename>file.txt</filename>
 </header>
 <orders>
  <order>
    <filename>file.txt</filename>
    <name>foo bar</name>
  </order>
  <order>
    <filename>file.txt</filename>
    <name>foo bar</name>
  </order>
  ...
 </orders>
</root>

In words i need to take tag and put it into every element. What would be the simplest way doing this with XSLT?

hs2d
  • 6,027
  • 24
  • 64
  • 103

2 Answers2

1

You need to start the coding with the identity transformation template

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

plus a template for your order elements

<xsl:template match="order">
  <xsl:copy>
    <xsl:apply-templates select="../../header/filename | node()"/>
  </xsl:copy>
</xsl:template>
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
0

First you need to create xslt stylesheet to transform your xml. The working example will look like this:

<?xml version="1.0" encoding="utf-16"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:template match="/root">
    <xsl:variable name="filename" select="header/filename"/>
    <xsl:element name="root">
        <xsl:for-each select="*">
            <xsl:choose>
            <xsl:when test="local-name()='orders'">
                <xsl:element name="orders">
                    <xsl:for-each select="*">
                        <xsl:element name="order">
                            <xsl:element name="filename" >
                                <xsl:value-of select="$filename"/>
                            </xsl:element>
                            <xsl:copy-of select="*"/>
                        </xsl:element>
                    </xsl:for-each>
                </xsl:element>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="."/>
            </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>


You can find how to transform xml documnent here : how to apply an xslt stylesheet in c#

Community
  • 1
  • 1
faent
  • 16
  • 1