Kon*_*che 9 java xml xpath parsing
目前我正在使用XPath Expression解析XML消息.它工作得很好.但是我有以下问题:
我正在解析XML的整个数据,因此我实例化每次调用xPath.evaulate
new InputSource
.
StringReader xmlReader = new StringReader(xml);
InputSource source = new InputSource(xmlReader);
XPathExpression xpe = xpath.compile("msg/element/@attribute");
String attribute = (String) xpe.evaluate(source, XPathConstants.STRING);
Run Code Online (Sandbox Code Playgroud)
现在我想更深入地了解我的XML消息并评估更多信息.为此我发现自己需要另一次实例化源代码.这需要吗?如果我不这样做,我会收到Stream关闭的例外情况.
McD*_*ell 12
将XML解析为DOM并保留对节点的引用.例:
XPath xpath = XPathFactory.newInstance()
.newXPath();
InputSource xml = new InputSource(new StringReader("<xml foo='bar' />"));
Node root = (Node) xpath.evaluate("/", xml, XPathConstants.NODE);
System.out.println(xpath.evaluate("/xml/@foo", root));
Run Code Online (Sandbox Code Playgroud)
这样可以避免多次解析字符串.
如果必须重用InputSource
不同的XML字符串,则可以将setter与不同的reader实例一起使用.