Java xPath/DOM - When importing a node into a document, xPath query is unable to find new node (and sub node)



I am trying to import a node into a 'new' DOM Document and then execute xPath queries on the newly imported nodes. The XML that I'm working with has no namespaces. I have followed the standard procedure to create a document, as shown:



Document newDoc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
newDoc = builder.newDocument();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
}


and to import the nodes...



// nodeToImport is a node from a prior xPath search (part of a node set)
Node docToRunXPathOn = newDoc.importNode(nodeToImport, true);


Later, when I try to run an xPath query such as



XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();

if (docToRunXPathOn != null) {
try {
XPathExpression expr = xpath.compile("//version_id/text()");
return (String)expr.evaluate(doc, XPathConstants.STRING);
} catch (XPathExpressionException e) {
logger.error(e);
}
}


The evaluation returns an empty string. A sample XML is below:



<?xml version="1.0" encoding="UTF-8"?>
<Version>
<version_id>51312</version_id>
<description>Some Description</description>
</Version>


The solution that I've employed is to serialize the DOM into a string, and then immediately parse that string to re-build the structure as a new DOM. This seems incredibly inefficient and backwards - what am I missing with this import and xPath? I had thought it might be because the node's parent and such are not being set properly, but when I did the clone/adopt method (or adopting after importing) the same behavior is seen.


Any answers/explanations/suggestions/thoughts appreciated.


No comments:

Post a Comment