Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if a node exists?

Tags:

xslt

xpath

I have a set of data called <testData> with many nodes inside.

How do I detect if the node exists or not?

I've tried

<xsl:if test="/testData">

and

<xsl:if test="../testData">

Neither one works. I'm sure this is possible but I'm not sure how. :P

For context the XML file is laid out like this

<overall>
 <body/>
 <state/>
 <data/>(the one I want access to
 </overall>

I'm currently in the <body> tag, though I'd like to access it globally. Shouldn't /overall/data work?

Edit 2: Right now I have an index into data that I need to use at anytime when apply templates to the tags inside of body. How do I tell, while in body, that data exists? Sometimes it does, sometimes it doesn't. Can't really control that. :)

like image 870
bobber205 Avatar asked Feb 09 '11 18:02

bobber205


3 Answers

Try count(.//testdata) &gt; 0.

However if your context node is textdata and you want to test whether it has somenode child or not i would write:

  <xsl:if test="somenode"> 
    ...
  </xsl:if>

But I think that's not what you really want. I think you should read on different techniques of writing XSLT stylesheets (push/pull processing, etc.). When applying these, then such expressions are not usually necessary and stylesheets become simplier.

like image 68
Alex Nikolaenkov Avatar answered Nov 01 '22 07:11

Alex Nikolaenkov


This XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="text()"/> <!-- for clarity only -->
    <xsl:template match="body">
        <xsl:if test="following-sibling::data">
            <xsl:text>Data occurs</xsl:text>
        </xsl:if>
        <xsl:if test="not(following-sibling::data)">
            <xsl:text>No Data occurs</xsl:text>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Applied to this sample:

<overall>
    <body/>
    <state/>
    <data/>(the one I want access to
</overall>

Will produce this correct result:

Data occurs

When applied to this sample:

<overall>
    <body/>
    <state/>
</overall>

Result will be:

No Data occurs
like image 33
Flack Avatar answered Nov 01 '22 07:11

Flack


This will work with XSL 1.0 if someone needs...

<xsl:choose>
    <xsl:when test="/testdata">node exists</xsl:when>
    <xsl:otherwise>node does not exists</xsl:otherwise>
</xsl:choose>
like image 3
Hrvoje Golcic Avatar answered Nov 01 '22 08:11

Hrvoje Golcic