B Polit
B Polit

Reputation: 190

XSL: Test if there is only one child node

I have some XML-Code that looks like:

<l>
    some text <app><rdg>text inside an app</rdg></app>
</l>
<l>
    <app><rdg>line with text inside an app</rdg></app>
</l>

I want to process the XML with XSLT and append different attributes to the output, depending on:

  1. If the line contains text and an <app> and an <rdg>with text in it
  2. If line contains only text, that is inside an <rdg>-Element

I tried the following solution, which does not work for me:

<xsl:for-each select="l">
        <xsl:choose>
            <xsl:when test="app/rdg">
                <myElement>
                    <xsl:attribute name="class" select="'case1'"/>
                </myElement>
            </xsl:when>
            <xsl:when
                test="app/rdg[not(../following-sibling::*) and 
    not(../preceding-sibling::*)]">
                <myElement>
                    <xsl:attribute name="class" select="'case2'"/>
                </myElement>
            </xsl:when>
        </xsl:choose>
    </xsl:for-each>

Is there a way to distinguish these two (or of course even more) cases?

Upvotes: 0

Views: 250

Answers (1)

Alejandro
Alejandro

Reputation: 1882

Your first condition

If the line contains text and an <app> and an <rdg> with text in it

It is equal to this XPath expression:

text() and app[rdg]

Your second condition

If line contains only text, that is inside an <rdg>-Element

It's equal to this XPath expression:

not(.//text()[not(parent::rdg)])

All these in the context of an l element.

Upvotes: 1

Related Questions