Altering a leaf node

D

daniel.bron

Hello,

Given a XML document, an XPath to a leaf node, and a string value, what
is the briefest XSLT transform to change that node's value to the
given string? The node is unique, unrepeated, and guaranteed to exist.

The real life scenario is an application's configuration file. I want
to extract a particular config parameter, do some non-trivial
transformations on it (external to XSLT) , then put the transformed
value back. How can I accomplish this?

-Dan
 
J

Joe Kesselman

Given a XML document, an XPath to a leaf node, and a string value, what
is the briefest XSLT transform to change that node's value to the
given string? The node is unique, unrepeated, and guaranteed to exist.

You can't "put back" a value using XSLT. What you do is generate a new
document that reflects the changes you want to make.

In this case: start with the identity transformation, then add one more
template which matches on that XPath and recreates the node with the
altered value. Almost any decent XSLT tutorial will describe this
approach, since it's a fairly standard stylesheet design.
 
D

daniel.bron

I read the W3C tutorial, and two others that came up early in Google.
But I'm still stumped. Can you point me at a good tutorial (or other
document) you like, that covers this?
 
J

Joseph Kesselman

Start with the identity template:

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

Then add a template to describe the exceptional behavior. If you're
feeling paranoid, you may want to push its priority up a step or two,
but that probably isn't necessary in this simple case. (XSLT's implied
priority rules are very weak, but generally they're strong enough that
anything specific takes precedence over node() and @*.)

<xsl:template match="/xpath/to/your/interesting/leaf_node">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:text>your new string value</xsl:text>
</xsl:copy>
</xsl:template>

Note that this assumes that if your leaf is an element, you really do
want to discard all its content and replace that with the new string --
even if it contains additional structure. If that isn't what you
intended, you'll have to think more precisely about what you _do_ want
to happen and write the appropriate transformation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top