views:

44

answers:

1

Could someone advise me what's wrong with the XSLT transformation below? I have stripped it down to a minimum.

Basically, I would like to have a parameter "title" replaced, but I cannot get it to run. The transformation simply ignores the parameter. I have highlighted the relevant bits with some exclamation marks.

Any advise is greatly appreciated.

public class Test {
    private static String xslt =
            "<?xml version=\"1.0\"?>\n" + 
            "<xsl:stylesheet\n" + 
            "        xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n" + 
            "        version=\"1.0\">\n" + 
            "    <xsl:param name=\"title\" />\n" + 
            "    <xsl:template match=\"/Foo\">\n" +
            "        <html><head><title>{$title}</title></head></html>\n" + // !!!!!!!!!!!
            "    </xsl:template>\n" +
            "</xsl:stylesheet>\n";

    public static void main(String[] args) {

        try {
            final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware( true );
            final DocumentBuilder db = dbf.newDocumentBuilder();
            final Document document = db.newDocument();
            document.appendChild( document.createElement( "Foo" ) );

            final StringWriter resultWriter = new StringWriter();
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer( new StreamSource( new StringReader( xslt ) ) );
            // !!!!!!!!!!!!!!!!!!
            transformer.setParameter( "title", "This is a title" );
            // !!!!!!!!!!!!!!!!!!
            transformer.transform( new DOMSource( document ), new StreamResult( resultWriter ) );

            System.out.println( resultWriter.toString() );
        } catch( Exception ex ) {
            ex.printStackTrace();
        }
    }
}

I'm using Java 6 without any factory-specific system properties set.

Thank you in advance!

+2  A: 
<html><head><title>{$title}</title></head></html>

The problem is in the above line.

In XSLT the {someXPathExpression} syntax can be used only in (some) attributes, and never in text nodes.

Solution:

Replace the above with:

<html><head><title><xsl:value-of select="$title"/></title></head></html>
Dimitre Novatchev
Thanks for your reply. How would I proceed if I wanted to try something like that: <img src="<xsl:value-of select="$host_name"/>/images/foobar.png" />Thanks!
digitalbreed
@digitalbreed: `<img src="{$host_name}">/images/foobar.png</img>`
Dimitre Novatchev
As noted, the `{bracket syntax}` is allowed in some attributes. The XSLT spec defines what those attributes are: Attribute Value Templates, see http://www.w3.org/TR/xslt#attribute-value-templates
Christian Semrau
@Christian-Semrau: Yes, this is wellknown. With the exception of the `select` attribute, AVTs are allowed for all other attributes.
Dimitre Novatchev