javaxmlxpathsaxon

Don't get any result using Saxon Xpath 2.0


I want to parse xml using xpath 2.0 or 3.0 expressions. I would like to use the most updated version for XPath, so I download Saxon jars. This is my code:

Processor proc = new Processor(false);
DocumentBuilder builder = proc.newDocumentBuilder();
XdmNode doc = builder.build(new File(file.getPath()));
XPathCompiler xpath = proc.newXPathCompiler();
XPathSelector selector = xpath.compile(mappingXPath.get(key)).load();
selector.setContextItem(doc);
for (XdmItem item : selector) {
    XdmNode node = (XdmNode) item;
    org.w3c.dom.Node element = (org.w3c.dom.Node) node.getExternalNode();
    System.out.println(element.getTextContent());
}

for example, xpath expression //mods/identifier[@type="doi"] for xml:

<?xml version="1.0" encoding="UTF-8"?>
<collection>
  <mods xmlns="http://www.loc.gov/mods/v3" xmlns:etd="http://www.ntltd.org/standards/metadata/etdms/1.0/etdms.xsd" xmlns:local="http://idea.library.drexel.edu" xmlns:mods="http://www.loc.gov/mods/v3" xmlns:datacite="https://schema.datacite.org/meta/kernel-4.0/metadata.xsd" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink">
    <identifier type="assetId">16</identifier>
<identifier type="doi">10.17918/D8VD4T</identifier>
 </mods>
</collection>

my selector is empty, why I don't get any result while I run the same expression and xml file in https://www.freeformatter.com/xpath-tester.html and it provide results?


Solution

  • XdmNode.getExternalNode() will only return a result if the XDM node is a wrapper/view of an external node such as a DOM node. A node built using the Saxon DocumentBuilder is a native XDM node, not a view of an external DOM node. If you want to use DOM with Saxon you can - just build the DOM node externally and wrap it using DocumentBuilder.wrap(domNode). But note that Saxon is 5 to 10 times slower when processing DOM nodes than when using its native XDM tree model.