Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XSLT to copy all nodes in XML, with support for special cases

Tags:

xml

xslt

Say I have a large XML file that the following structure:

<MyXml>
  <Data1>
    <Node1>1234</Node1>
    <Node2>abc<Node2>
    <Node3>gfdf</Node3>
    ...
    <Node10000>more text</Node10000>
  </Data1>
  <Data2>
    ...
  </Data2>
</MyXml>

I want to transform this XML into another XML that looks exactly the same, but has a certain string concatinated to a certain node, say Node766. I am using an XSLT of course and wondering how I can tell it to copy everyhing as-is except for Node766, where I have to do something before outputing it.

like image 786
del.ave Avatar asked May 03 '11 22:05

del.ave


People also ask

How do I copy nodes in XSLT?

XSLT <xsl:copy-of> The <xsl:copy-of> element creates a copy of the current node. Note: Namespace nodes, child nodes, and attributes of the current node are automatically copied as well! Tip: This element can be used to insert multiple copies of the same node into different places in the output.

How XSLT works with XML?

XSLT is used to transform XML document from one form to another form. XSLT uses Xpath to perform matching of nodes to perform these transformation . The result of applying XSLT to XML document could be an another XML document, HTML, text or any another document from technology perspective.

Can we use XQuery in XSLT?

For example, you can use XQuery to extract data from an XML database, and XSLT to present the results to users on the web.


2 Answers

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

<!--Identity template, 
        provides default behavior that copies all content into the output -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--More specific template for Node766 that provides custom behavior -->
    <xsl:template match="Node766">  
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
            <!--Do something special for Node766, like add a certain string-->
            <xsl:text> add some text </xsl:text>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
like image 141
Mads Hansen Avatar answered Nov 13 '22 05:11

Mads Hansen


Start with an identity transform, and include a template match for your exception.

like image 28
Don Roby Avatar answered Nov 13 '22 03:11

Don Roby