Skip to content

Instantly share code, notes, and snippets.

@BDF
Last active October 1, 2016 20:51
Show Gist options
  • Save BDF/c2c201113fa248e36319 to your computer and use it in GitHub Desktop.
Save BDF/c2c201113fa248e36319 to your computer and use it in GitHub Desktop.
A very small example of using saxon:evaluate and saxon:linenumber(). I was having trouble getting the saxon:evaluate function to work correctly. The solution was very simple. When creating the processor pass in 'true' instead of 'false' (which is what most of the saxon examples use).
import net.sf.saxon.s9api.*;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
public class Main {
public static void main(String[] args) throws SaxonApiException {
String bookXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<books>\n" +
" <book category=\"reference\">\n" +
" <author>Nigel Rees</author>\n" +
" <title>Sayings of the Century</title>\n" +
" <price>8.95</price>\n" +
" </book>\n" +
"</books>";
String xslt = "<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n" +
" xmlns:saxon=\"http://saxon.sf.net/\">\n" +
" <xsl:param name='xPathToValue'/>\n" +
" <xsl:template match=\"/\">\n" +
" <xsl:copy-of select=\"saxon:evaluate($xPathToValue)\" xmlns:saxon=\"http://saxon.sf.net/\"/>\n" +
" <xsl:value-of select=\"saxon:line-number()\"/>\n" +
" </xsl:template>\n" +
" <xsl:template name=\"otherwise\" match=\"text()|@*\"/>\n" +
"</xsl:stylesheet>";
// If you are getting a: XPST0017 XPath syntax error at in {saxon:evaluate }:
// Cannot find a matching argument function named {http://saxon.sf.net/}
// Saxon extension functions are not available under Saxon-HE
// It may be because you are passing 'false' instead of 'true' when creating the Processor.
// Saxon
// public Processor(boolean licensedEdition)
Processor proc = new Processor(true);
try (StringReader xmlReader = new StringReader(bookXml);
StringReader xsltReader = new StringReader(xslt)) {
DocumentBuilder docBuilder = proc.newDocumentBuilder();
XdmNode xdmNode = docBuilder.build(new StreamSource(xmlReader));
XsltCompiler xsltCompiler = proc.newXsltCompiler();
XsltExecutable xsltExe = xsltCompiler.compile(new StreamSource(xsltReader));
XdmDestination xdmDestination = new XdmDestination();
XsltTransformer trans = xsltExe.load();
trans.setParameter(new QName("xPathToValue"), new XdmAtomicValue("/books/book/author"));
trans.setInitialContextNode(xdmNode);
trans.setDestination(xdmDestination);
trans.transform();
System.out.println(xdmDestination.getXdmNode().toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment