Detect if node exists?

I have a dataset called <testData> with many nodes inside.

How to determine if a node exists or not?

I tried

 <xsl:if test="/testData"> 

and

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

None of them work. I am sure it is possible, but I do not know how to do it .: P

In the context of XML, the file is as follows

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

I am now in the <body> , although I would like to access it all over the world. Should /overall/data work?

Edit 2: Right now I have an index in the data that I need to use anytime when you apply templates to tags inside the body. How can I say while in the body this data exists? Sometimes this happens, sometimes it is not. I can’t control it. :)

+4
source share
3 answers

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

However, if your node context is equal to textdata , and you want to check if it has somenode child or not, I would write:

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

But I think that is not what you really want. I think you should read about the different methods of writing XSLT styles (push / pull processing, etc.). When used, such expressions are usually not needed, and styles become simpler.

+8
source

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> 

Applies to this sample:

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

Will produce the correct result:

 Data occurs 

When applied to this sample:

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

The result will be:

 No Data occurs 
+3
source

This will work with XSL 1.0 if anyone needs to ...

 <xsl:choose> <xsl:when test="/testdata">node exists</xsl:when> <xsl:otherwise>node does not exists</xsl:otherwise> </xsl:choose> 
+3
source

Source: https://habr.com/ru/post/1339072/


All Articles