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

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 that will produce an exact copy of an existing XML file with a simple change?

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

<?xml version="1.0" encoding="utf-8"?> <Employees> <!-- ... --> <Employee name="Martin"> <Position number="50" /> </Employee> <!-- ... --> </Employees> 
+4
source share
3 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> 
+5
source

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> 
+4
source
 <xsl:template match="/Employees/Employee/Position"> <xsl:attribute name="number">100</xsl:attribute> </xsl:template> 
-1
source

Source: https://habr.com/ru/post/1401912/


All Articles