Skip to content

Instantly share code, notes, and snippets.

@BDF
Last active September 13, 2016 14:14
Show Gist options
  • Save BDF/549959faeadc056307d8be11530bbc1c to your computer and use it in GitHub Desktop.
Save BDF/549959faeadc056307d8be11530bbc1c to your computer and use it in GitHub Desktop.
package com.proquest.xslt;
import java.io.StringReader;
import java.util.Iterator;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathExecutable;
import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmNode;
/**
* Created by BDF on 9/13/16.
*
* @author BDF
*/
public class SaxonXPathGist {
public static void main(String [] args) throws SaxonApiException {
String xPath1 = "for $a in /test " +
" return " +
" (if ($a/value[@cat=\"mythology\"]) then " +
" $a/value[@cat=\"mythology\"] else " +
" \"\")";
String xPath2 = "for $a in /test/value " +
" return " +
" if ($a[@cat='mythology']) then " +
" $a[@cat='mythology'] else " +
"\"\"";
String xml = "<test>\n" +
" <value cat=\"fiction\">At the edge of the orchard</value>\n" +
" <value cat=\"mythology\">Hero with a thousand faces</value>\n" +
" <value cat=\"fiction\">Spill simmer falter wither</value>\n" +
"</test>";
Processor proc = new Processor(true);
XPathCompiler xPathCompiler = proc.newXPathCompiler();
xPathCompiler.setLanguageVersion("3.1");
DocumentBuilder docBuilder = proc.newDocumentBuilder();
XdmNode xdmNode = docBuilder.build(new StreamSource(new StringReader(xml)));
printResults(xPath1, xPathCompiler, xdmNode);
printResults(xPath2, xPathCompiler, xdmNode);
}
private static void printResults(String xPath1, XPathCompiler xPathCompiler, XdmNode xdmNode) throws SaxonApiException {
XPathExecutable xPathExe = xPathCompiler.compile(xPath1);
final XPathSelector selector = xPathExe.load();
selector.setContextItem(xdmNode);
Iterator<XdmItem> iter = selector.iterator();
while (iter.hasNext()) {
System.out.println(String.format("'%s'", iter.next().getStringValue()));
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment