简体   繁体   中英

How can I copy data from an xml file into another xml file using xsl at a specified location

I am trying to copy data from file1 to file2 using xsl transformation. I am able to copy the data, but not at the location I desire. Please help me have the data copied to the right place. Here is my code:

file1.xml:

<Org>
    <Department name="Environmental" />
</Org>

file2.xml:

<Org>
    <Division>Engineering</Division>
    <Address>123 Elm Street</Address>
</Org>

result.xml:

<Org>
    <Division>Engineering</Division>
    <Address>123 Elm Street</Address>

</Org>
    <Department name="Environmental" />

Desired output:

<Org>
    <Department name="Environmental">
        <Division>Engineering</Division>
        <Address>123 Elm Street</Address>
    </Department>
</Org>

Here is the code from my xsl file:

  <xsl:template match="//*[local-name()='Org'][*[local-name()='Department']]">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
                <xsl:copy>
                    <xsl:copy-of select="document($lookup)/Agency/Division" />
                    <xsl:copy-of select="document($lookup)//Agency/Address" />
                </xsl:copy>
            <xsl:apply-templates select="node()" />
        </xsl:copy>     

Can somebody please help me in fixing the issue.

Thanks for the help.

Change your XSLT template to the following. The variable lookup should contain the filename and path of file2.xml .

<!-- Copies the 'Org' node of file1.xml and applies the templates on the child elements -->
<xsl:template match="/*[local-name()='Org']">
  <xsl:copy>
    <xsl:apply-templates select="*" />
  </xsl:copy>
</xsl:template>

<!-- Copies the 'Department' node of file1.xml and then includes the values from file2.xml (in $lookup variable) -->
<xsl:template match="*[local-name()='Department' and parent::*[local-name()='Org']]">
  <xsl:copy>
    <xsl:copy-of select="@*" />              <!-- Copy the @name attribute (and possible others) -->
    <xsl:copy-of select="document($lookup)/Org/Division" />
    <xsl:copy-of select="document($lookup)/Org/Address" />
    <xsl:apply-templates select="node()" />  
  </xsl:copy>     
</xsl:template>

The output is:

<?xml version="1.0"?>
<Org>
    <Department name="Environmental">
        <Division>Engineering</Division>
        <Address>123 Elm Street</Address>
    </Department>
</Org>

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