简体   繁体   中英

XSLT move one xml tag value to other

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?

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>

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#

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