Testing text node in XSLT
xpath, xslt, xslt-2.0
Solution
How can I write a test that selects only the text nodes of `<firstElement>`?
It is really difficult to understand your question:
First, a test does not select anything - I suppose you mean you want the test to pass text nodes only.
Next, when you do:
<xsl:for-each select="child::*">
you are selecting element nodes only - so any subsequent test that passes text nodes only will always return false.
It's also not clear why you need to select any nodes that are not text nodes in the first place, and then test them and pass only text nodes. But supposing that's really what you want to do, you can do it this way:
<xsl:template match="firstElement">
<output>
<!-- select all child nodes -->
<xsl:for-each select="node()">
<!-- pass only text nodes -->
<xsl:if test=". instance of text()">
<xsl:copy/>
</xsl:if>
</xsl:for-each>
</output>
</xsl:template>
This returns:
<output>text1text2</output>
which is the same result returned by the much simpler:
<xsl:template match="firstElement">
<output>
<xsl:copy-of select="text()"/>
</output>
</xsl:template>
I have tried with `text()`, but it only works for the child text node of the contextual node and `self::text()` doesn't seem to be a proper Xpath.
I am not sure why you think so.
<xsl:if test="self::text()">
works just as well - and has the advantage of being backward-compatible with XSLT 1.0.
Problem
I have the following mix-content element: ``` <firstElement type="random">text1<secondElement>random_value</secondElement>text2</firstElement> ``` I want to make a `for-each` loop on `<firstElement>` child nodes with a nested `if` condition, for example: ``` <xsl:for-each select="child::*"> <xsl:if test="some test"> <xsl:copy> </xsl:if> </xsl:for-each> ``` How can I write a `test` that selects only the text nodes of `<firstElement>`? I have tried with `text()`, but it only works for the child text node of the contextual node and `self::text()` doesn't seem to be a proper Xpath. I also tried to use XSLT 2.0 `instance of` to test against `xs:string` but it didn't work either.