1 | initial version |
One effective way to substitute node values based on certain sub-node conditions is to use XPath expressions to select the sub-nodes that meet the condition and then use XSLT templates to modify the node values. Here is an example using XSLT:
Suppose we have an XML document that contains a list of books and we want to replace the price of all books that have an author named "Stephen King" with a new price of 10. We can use the following XSLT stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Identity template copies all nodes unchanged -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<!-- Replace price of Stephen King books with 10 -->
<xsl:template match="book[author='Stephen King']/price">
<price>10.00</price>
</xsl:template>
</xsl:stylesheet>
The identity template copies all nodes unchanged, while the second template matches any book
node where the author
sub-node is equal to "Stephen King". For each matching book
, the template replaces the price
sub-node with a new value of 10.00.
When we apply this stylesheet to our XML document, all books with Stephen King as the author will have their price replaced with 10:
<library>
<book>
<title>The Shining</title>
<author>Stephen King</author>
<price>10.00</price>
</book>
<book>
<title>1984</title>
<author>George Orwell</author>
<price>12.99</price>
</book>
<book>
<title>The Stand</title>
<author>Stephen King</author>
<price>10.00</price>
</book>
</library>