简体   繁体   中英

Inserting nodes from a XML to another XML file using xslt

So I have an xml file like this:

<?xml version="1.0"?>
<class>

    <students>
        <name origin="English" firstname="Jeff" lastname="Richards"/>
        <name origin="French" firstname="Martel" lastname="Francois"/>
    </students>

    <teachers>
        <name origin="Spanish" firstname="Enrique" lastname="Rosa"/>
    </teachers>

</class>

And have another xml file like this:

 <?xml version="1.0"?>
    <name origin="English" firstname="Richard" lastname="Priestly"/>
    <name origin="Russian" firstname="Alexey" lastname="Romanov"/>

Using xslt, how can I add the two elements in the second file into the student element in the first file? In other words, how can I create a file that looks like this:

<?xml version="1.0"?>
    <class>

        <students>
            <name origin="English" firstname="Jeff" lastname="Richards"/>
            <name origin="French" firstname="Martel" lastname="Francois"/>
            <name origin="English" firstname="Richard" lastname="Priestly"/>
            <name origin="Russian" firstname="Alexey" lastname="Romanov"/>
        </students>

        <teachers>
            <name origin="Spanish" firstname="Enrique" lastname="Rosa"/>
        </teachers>

    </class>

If it is not possible using xslt, is it doable using XPath?

Thanks a bunch!

Here is one way, assuming you make the second file well-formed by adding a 'students' root node and name it 'students.xml':

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output indent="yes" method="xml"/>

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

<xsl:template match="students">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:for-each select="document('students.xml')/students/name">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

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