开发者

XSLT parameter not replaced

开发者 https://www.devze.com 2022-12-29 15:28 出处:网络
Could someone advise me what\'s wrong with the XSLT transformation below? I have stripped it down to a minimum.

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 e开发者_开发百科xclamation 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!


<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号