Re: [xslt] ancestor-or-self question



There are a couple of things the beginner needs to know in order not to
get lost.

First, general questions about XSL (which includes XSLT and XSL/FO), as
opposed to processor specific questions, are best asked on XSL-List:

    http://www.mulberrytech.com/xsl/xsl-list/

Second, the most important language idiom in XSLT is the so-called
"identity template", or "copy template". This transforms the document
without making any changes to it other than those entailed by the XDM,
which is the data model XSLT operates on.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
  <!-- This is the identity template. -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Now to your question.

vincent leycuras schrieb:
I want to transform the following XML:

<root>
<level1>
        <level2>a</level2>
        <level2>b</level2>
        ...
</level1>
</root>

to the following XML:

<root>
<level1>
        <level2>other_value</level2>
</level1>
</root>

You seem to want to keep the general structure except the level2
elements. The way you solve this in XSLT is by taking the identity
template and then specifying your modifications. In this case, you want
to take control of the processing at /root/level1. So you say:

  <!-- The thing inside @match is called a "pattern". In this case, you
  can simply say "level1". If you had level1 elements at multiple levels
  and only wanted to take control of those directly under the document
  element, you could say /*/level1, or, more explicitly, /root/level1.
  -->
  <xsl:template match="level1">
    <xsl:copy><!-- copy this element -->
      <!-- Don't process the input document.
      Instead, specify literally what you want. -->
      <level2>other_value</level2>
    </xsl:copy>
  </xsl:template>

Add this template to the above stylesheet module, and it'll work.

[...] spent a whole day trying to figure it out and browsed all web
resources I could find, I'm at a loss.

In addition to XSL-List, for XSLT 1.0 consult:

* http://www.jenitennison.com/xslt/
* XSLT 1.0 Pocket Reference by Evan Lenz (O'Reilly)
* http://www.dpawson.co.uk/xsl/

Michael Ludwig


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]