XSL select only nodes which contain a specific child node

W

William Krick

Given the following extremely simplified XML...

<AA>
<BB></BB>
<BB><CC>foo</CC></BB>
<BB></BB>
<BB><CC>bar</CC></BB>
</AA>

....is there an easy way to use and XSL select to get only the <BB>
nodes which have a <CC> child node?

<xsl:for-each select="AA/BB">

Gives me 4 nodes:

<BB></BB>
<BB><CC>foo</CC></BB>
<BB></BB>
<BB><CC>bar</CC></BB>


<xsl:for-each select="AA/BB/CC">

Gives me 2 nodes, but it's at the CC level and I need it to be at the
BB level because there's a bunch of other nodes there that need to be
processed as well.

<CC>foo</CC>
<CC>bar</CC>


I'm thinking that there must be some sort of conditional select XPATH
that will get me what I need:

<BB><CC>foo</CC></BB>
<BB><CC>bar</CC></BB>


Any tips?
 
M

Martin Honnen

William said:
Given the following extremely simplified XML...

<AA>
<BB></BB>
<BB><CC>foo</CC></BB>
<BB></BB>
<BB><CC>bar</CC></BB>
</AA>

...is there an easy way to use and XSL select to get only the <BB>
nodes which have a <CC> child node?

<xsl:for-each select="AA/BB">

XSLT uses XPath to select nodes and with XPath you can do
/AA/BB[CC]
to select those 'BB' child elements of the 'AA' root element which have
at least one 'CC' child element.

With XPath 2.0 you could also write
/AA/BB[exists(CC)]
which might be clearer and more intuitive for beginners.
 
W

William Krick

XSLT uses XPath to select nodes and with XPath you can do
   /AA/BB[CC]
to select those 'BB' child elements of the 'AA' root element which have
at least one 'CC' child element.

Thank you, that's exactly what I needed.
I knew what I wanted to do, I just didn't know the XPath syntax. :)
 
Joined
Mar 18, 2011
Messages
2
Reaction score
0
How to select a node in this case?

I have an xml file:
<AA>
<BB>fgh</BB>
<BB>
<CC>asd</CC>
<DD>KEY</DD>
</BB>
<BB>
<CC>dsgf</CC>
</AA>

I need to select the BB nodes that have a child node CC and also that have a child node which has value "KEY", i.e. i should be able to select only the second BB node. Would this work?:

<xsl:for-each select="AA/BB[CC and DD='KEY']">
...
</xsl:for-each>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,783
Latest member
RickeyDort

Latest Threads

Top