我正在对输入 XML 进行 XSL 转换,然后我需要在结果文档上使用 XPath 提取一些值。但是在使用 XSL 结果节点时,XPath 表达式可能总是返回 null。但是如果我将 XSL 生成的文档存储在一个文件中,然后重新加载它。XPath 表达式返回相应的节点。
这是我的代码(为了方便起见,实用程序已被删除):
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());
}
}
只需注释或删除“// Store 然后重新加载文件”下面的 3 行,测试将不再通过。
我完全陷入困境,欢迎任何帮助。