Ahmad Al-Sanie
Ahmad Al-Sanie

Reputation: 3785

XSL: how to check if any of the ancestors of the current node is a specific node

Let's say that we have this XML:

          <ce:table id="table2">
                <ce:label>Table 2</ce:label>
                <ce:caption >
                    <ce:simple-para >Hello</ce:simple-para>
                </ce:caption>
                <ce:alt-text >Table 2</ce:alt-text>
                <tgroup cols="2">
                    <colspec colname="col1"/>
                    <colspec colname="col2"/>
                    <thead valign="top">
                        <row rowsep="1">
                            <entry align="left">Sub1</entry>
                            <entry align="left">Sub2</entry>
                        </row>
                    </thead>
                    <tbody>
                        <row>
                            <entry role="rowhead" align="left">
                                <ce:list id="list1">

                                </ce:list>
                            </entry>
                        </row>
                    </tbody>
                </tgroup>
            </ce:table>

How to check if ce:table node has a ce:list node in this case the XSLT condition should return true.

Any ideas!

Upvotes: 0

Views: 589

Answers (3)

zx485
zx485

Reputation: 29052

If your current node is

/data/ce:table

you can check the existence of a ce:list subnode with

<xsl:if test=".//ce:list">

.// means all nodes descending from current node, without considering depth.

Upvotes: 2

Tomalak
Tomalak

Reputation: 338336

Of course this:

<xsl:when test="ce:table/*[local-name() = 'ce:list'] ">

Didn't work, because

  • local-name() explicitly gives you names without prefixes, it would never return ce:list
  • the ce:list you refer to is not a direct child of ce:table, but a descendant.

How to check if ce:table node has a ce:list node

Like this:

<xsl:when test="ce:table//ce:list"> ... </xsl:when>

Checking for the existence of a node is done by writing an XPath expression that selects it. If the node does not exist, the expression returns an empty node-set, which evaluates to false in a Boolean context.

Boolean contexts are the tests in <xsl:if> or <xsl:when>, but also the predicates in a more complex XPath expression:

ce:table[.//ce:list]/ce:label

selects all <ce:label> children of <ce:table>, but only under the condition that that <ce:table> has a <ce:list> descendant somewhere.

Upvotes: 2

Martin Honnen
Martin Honnen

Reputation: 167716

If you want to select descendants with XPath then use e.g. ce:table/descendant::ce:list or ce:table//ce:list. Inside the test attribute that selection would then yield true if any such node exists.

Upvotes: 2

Related Questions