Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XSLT- Getting First Element With Text

Status
Not open for further replies.

BoulderBum

Programmer
Joined
Jul 11, 2002
Messages
2,179
Location
US
I have a stylesheet that processes an HTML page converted to a form of XML. It usually works, but sometimes the layout of the returned page changes.

One page, the format might be:

Code:
<td customid="32">some text</td>

another page might be like this:

Code:
<td customid="33">
   <b cusomid="34">some different text</b>
</td>

I can reference the TD node just fine, but is there a simple way to find the first child node containing text (without xsl:if or for-each)?

I was thinking something like

td//(firstnode where text isn't empty)
 
Here is an example of one way of doing it:

Code:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<td customid="30"></td>
<td customid="32">
    <b>some text</b>
</td>
</body>

Code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
 
<xsl:stylesheet version="1.0" 
     xmlns:xsl="[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform">[/URL]

<xsl:output method="html"/>

<xsl:template match="/">
     <xsl:apply-templates select="body"/>
</xsl:template>

<xsl:template match="body">
     Text: <xsl:value-of select="normalize-space(td[string()][1])"/>
     Position: <xsl:value-of select="count(td[string()][1]/preceding-sibling::td ) + 1"/>
</xsl:template>

</xsl:stylesheet>

I have included how to determine the position of the
element just in case you have a need for it. The
normalize-space() is only for pretty-printing.

Enjoy
- Finnbarr
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top