I'm doing a XSL transformation on a input XML then I need to extract some values using XPath on the resulting document. But may XPath expression always return null when using the XSL result Node. But If I store the XSL resulting document in a file then reload it. the XPath expression returns the corresponding Node.
Here is my code (utility fonctions have been removed for lisibility) :
public class XmlTest {
@Test
public void testWithNativeJavaApi() throws Exception {
InputStream instream = resolveClasspathFile("xslt/xslt-test-transform-2.xsl");
StreamSource xsltSource = new StreamSource(instream);
DOMSource domSource = loadXmlFromClasspathFile("xslt/xslt-test-input-2.xml");
prettyPrint(domSource.getNode());
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
DOMResult domResult = new DOMResult();
transformer.transform(domSource, domResult);
Node node = domResult.getNode();
// Store then reload the file
// Uncommenting those 3 lines will make the test pass
// File xslOutputfile = new File("target", "xsl-ouput.xml");
// prettyPrint(node, new FileOutputStream(xslOutputfile));
// node = loadXmlFromInputStream(new FileInputStream(xslOutputfile)).getNode();
XPath xPathProcessor = XPathFactory.newInstance().newXPath();
XPathExpression xpathExpression = xPathProcessor.compile("/Message/Out/Personne/CodeCivilite");
System.out.println();
Node resultNode = (Node) xpathExpression.evaluate(node, XPathConstants.NODE);
if (resultNode != null) {
System.out.println(resultNode.getNodeName() + "=" + resultNode.getTextContent());
} else {
System.out.println("Node is null");
}
assertNotNull("XPath expression returned null node", resultNode);
assertEquals("CodeCivilite", resultNode.getNodeName());
assertEquals("M.", resultNode.getTextContent());
}
}
Juste comment or remove the 3 lines below "// Store then reload the file" and the test won't pass anymore.
I'm completely stuck, any help is welcome.