Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XSLT to update a single value in an XML?

Tags:

xml

xslt

I have a giant XML file in which I would like to update a single value. Is there a way to write an XSLT file which will produce an exact copy of the existing XML file with a simple change?

For instance, let's say I have the following XML and that I want to change the position number of employee Martin to 100. How can I do this?

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <!-- ... -->

  <Employee name="Martin">
    <Position number="50" />
  </Employee>

    <!-- ... -->
</Employees>
like image 422
Martin Avatar asked Feb 22 '23 03:02

Martin


2 Answers

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

    <!--Identity template that will copy every
        attribute, element, comment, and processing instruction
        to the output-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--more specific template match on @number that will 
        change the value to 100-->
    <xsl:template match="Employee[@name='Martin']/Position/@number">
        <xsl:attribute name="number">100</xsl:attribute>
    </xsl:template>

</xsl:stylesheet>
like image 116
Mads Hansen Avatar answered Mar 03 '23 02:03

Mads Hansen


Start with an identity template

<xsl:template match="*">
 <xsl:copy>
  <xsl:copy-of select="@*"/>
  <xsl:apply-templates/>
 </xsl:copy>
</xsl:template>

add one template for your change

<xsl:template match="Employee[@name='Martin']/Position">
 <Position number="100" />
</xsl:template>
like image 43
David Carlisle Avatar answered Mar 03 '23 03:03

David Carlisle