Re: [xsl] (simple?) xpath question

Subject: Re: [xsl] (simple?) xpath question
From: Evan Lenz <evan@xxxxxxxxxxxx>
Date: Fri, 29 Aug 2008 13:07:15 -0700
Hi Mark,

XPath node-set expressions return *references* to nodes, not copies. In other words, you can't create new nodes with an XPath expression. You need XSLT to do that.

How you write the stylesheet depends on whether you're interested in singling out <b> nodes for exclusion, or <a> and <c> nodes for inclusion.

In the first case, you'd want a modified identity transformation:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
               version="1.0">

 <!-- By default, copy all nodes unchanged -->
 <xsl:template match="@* | node()">
   <xsl:copy>
     <xsl:apply-templates select="@* | node()"/>
   </xsl:copy>
 </xsl:template>

 <!-- But skip <b> elements and only process their contents -->
 <xsl:template match="b">
   <xsl:apply-templates/>
 </xsl:template>

</xsl:stylesheet>

Note that with this approach, you're singling out the <b> element for exclusion (excepting its content).

If what you want instead is to single out the <a> and <c> nodes for inclusion and strip out everything else, you'd write it a bit differently:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
               version="1.0">

 <!-- By default, copy <a> and <c> elements -->
 <xsl:template match="a | c">
   <xsl:copy>
     <xsl:apply-templates select="@* | node()"/>
   </xsl:copy>
 </xsl:template>

 <!-- But skip by every other element -->
 <xsl:template match="*">
   <xsl:apply-templates/>
 </xsl:template>

</xsl:stylesheet>

The above two stylesheets produce the exact same output for the sample document you provided. One distinction however is that the second one won't copy comments and processing instructions, whereas the first one will. The second one relies implicitly on the built-in template rule for text nodes to copy the text through.

Evan


mark bordelon wrote:
All *help*!
What is the best way to query xml with xpath to get a disjoint nodelist? Specifically i want to include just the root node alongwith a descendent node. XML:
<a>
<b>
<c>
</c>
</b>
</a>
XPATH:
//c
DESIRED RESULT NODELIST:
i.e. not this:
<c>
</c>
but rather this:
<a>
<c>
</c>
</a>

Current Thread