入力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());
}
}
コメントするか、「//保存してからファイルをリロードする」の下の3行を削除すると、テストに合格しなくなります。
私は完全に立ち往生しています、どんな助けでも大歓迎です。