Ask Your Question
0

What is the most effective way to substitute node values based on certain sub-node conditions?

asked 2023-07-16 21:56:41 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-16 22:19:01 +0000

david gravatar image

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>
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-16 21:56:41 +0000

Seen: 11 times

Last updated: Jul 16 '23