Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create Element in XSLT When Copying Using Templates

Tags:

xml

xslt

I'm trying to create an element in an XML where the basic content is copied and modified.

My XML is something like

<root>
  <node>
     <child>value</child>
     <child2>value2</child2>
  </node>
  <node2>bla</node2>
</root>

The number of children of node may change as well as the children of root. The XSLT should copy the whole content, modify some values and add some new.

The copying and modifying is no problem:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" encoding="UTF-8"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy> 
  </xsl:template>
</xsl:stylesheet>

(+ further templates for modifications).

But how do I add a new element in this structure on some path, e.g. I want to add an element as the last element of the "node" node. The "node" element itself always exists.

like image 878
John Dumont Avatar asked Mar 31 '10 18:03

John Dumont


People also ask

How do I use XSLT templates?

The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a "select" attribute to the <xsl:apply-templates> element, it will process only the child elements that matches the value of the attribute.

How do you call a template in XSLT?

The xsl:call-template element is used to invoke a template by name. By invoke, we mean that the named template is called and applied to the source document. If a template does not have a name, it cannot be called by this element. The xsl:template element is used to create a template.

What does xsl template element do?

The <xsl:template> element is used to build templates. The match attribute is used to associate a template with an XML element. The match attribute can also be used to define a template for the entire XML document. The value of the match attribute is an XPath expression (i.e. match="/" defines the whole document).


1 Answers

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" encoding="UTF-8"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy> 
  </xsl:template>
  <xsl:template match="node">
    <node>
      <xsl:apply-templates select="@*|node()"/>
      <newNode/>
    </node> 
  </xsl:template>
</xsl:stylesheet>
like image 148
dkackman Avatar answered Sep 24 '22 17:09

dkackman