Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conditional XPath query - is it possible

Status
Not open for further replies.

comma

Programmer
Feb 12, 2003
24
FI
Hi,

I was wondering if it's possible to do conditional queries with
XPath 1.0 or 2.0?

We can have queries defined with union operator like this:

E.g. if we would have the following XML -structure:
Code:
<documentRoot>

<!-- Test data --> 
<?value="2"?> 
<parent name="data" > 
   <child id="1"  name="alpha" >Some Text</child> 
   <child id="2"  name="beta" > 
      <grandchild id="2.1"  name="beta-alpha" ></grandchild> 
      <grandchild id="2.2"  name="beta-beta" ></grandchild> 
   </child> 
   . . .

And we would apply the following Xpath query:
Code:
//parent[@name="data"]/child[@id="1"]/text() |  
//parent[@name="data"]/child[@id="2"]/@name

It would match to the following elements:
- Some Text from child id=1
- beta from child id=2's name -attribute


But what I'd like to do is that if the first query matches:
Code:
	//parent[@name="data"]/child[@id="1"]/text()

then it would not run the second one (//parent[@name="data"]/child[@id="2"]/@name), but
would return the results from query 1 (-> "Some text").

What I'm looking for is kind of "or" -operator, which could be then used to run the
queries conditionally.

I was wondering is it possible with XPath itself or should I add some logic into my
application to handle the queries in this case? The application applies the queries
to different XML "streams", where we can have some variation in elements, thus the
conditional queries could be useful (then no need to add handling logic to the application
if XPath supports this).

Thanks.

-comma-
 
In xslt2.0 this is possible. Like this, apart from some formatting.
[tt]
<xsl:template match="parent">
<xsl:value-of select="(if (child[@id='1']) then child[@id='1'] else child[@id='2']/@name)" />
</xsl:template>
[/tt]
My understanding of what you said
> - Some Text from child id=1
as the existence of some child node with id="1". If you actually meant matching specific "Some Text" as its child of node with id="1", you have to alter the conditional above and the reasoning would be the same.

ps: the pi as it stands is incorrect.
 
Risk of some confusion on the match, I implicitly assume some apply-templates like this so that the context of parent is always with name='data'.
[tt]
<xsl:template match="/">
<xsl:apply-templates select="//parent[@name='data']" />
</xsl:template>
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top