View Full Version : XSLT: Selecting elements by length of content text?

Alex Vincent
06-24-2002, 01:44 AM
Here's an interesting situation. I'm working on an XML language for geometry, but I have a small problem in rendering a symbolism for arcs, rays and lines. For line segments, it's pretty simple: I associate a CSS styling with the element in question:

geo:line[ends="both"] {
text-decoration: overline

But beyond that, I need a little help...

For instance, with an arc:

<geo:arc id="ABC">...</geo:arc>

the presentation would need to be in the format:

<svg:g transform="translate(10,20)">
<svg:path d="M 0 10 A 20 10 0 0 1 26 10" fill="none" stroke="#000000" />
<svg:text x="0" y="20" font-family="Times New Roman">ABC</svg:text>

With a two-letter id attribute for geo:arc, I'd need:

<svg:g transform="translate(10,0)">
<svg:path d="M 0 10 A 20 20 0 0 1 18 10" fill="none" stroke="#000000" />
<svg:text x="0" y="20" font-family="Times New Roman">AB</svg:text>

A little different, obviously. So I'm wondering how to construct the <xsl:template>...</xsl:template> match attribute to distinguish between a two-character text content and a three-character text content.


06-24-2002, 03:17 AM
Say you want to check the length of the @id node of the context node:


Will return that number, so you can attach that as a predicate with a =2 to select only nodes with @id value equal to 2.

A quick example document and XSL document:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>

<test id="aa">Element with id = "aa"</test>
<test id="aaa">Element with id = "aaa"</test>
<test id="ab">Element with id = "ab"</test>
<test id="ac">Element with id = "ac"</test>
<test id="abb">Element with id = "abb"</test>

And the XSLT document:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
All elements with id lengths = 2:
<xsl:apply-templates select="docEl/test[string-length(string(@id)) = 2]"/>

<xsl:template match="test">
<xsl:value-of select="."/>

Works beautifully in Mozilla 1.0 and IE6.

Alex Vincent
06-24-2002, 03:23 AM
Thanks, Jason. Now if you'd only turn off your smileys... :thumbsup:

06-24-2002, 03:27 AM
Originally posted by Alex Vincent
Thanks, Jason. Now if you'd only turn off your smileys... :thumbsup:

Oops, you could have turned them off yourself you know Mr. Moderator ;).

Anyway, just disabled them, and proudly proclaiming post #100. :D