避免在Java中使用XPath重复实例化InputSource
目前,我正在使用XPath表达式解析XML消息。它工作得很好。但是,我有以下问题: 我正在解析XML的全部数据,因此每次调用避免在Java中使用XPath重复实例化InputSource,java,xml,parsing,xpath,Java,Xml,Parsing,Xpath,目前,我正在使用XPath表达式解析XML消息。它工作得很好。但是,我有以下问题: 我正在解析XML的全部数据,因此每次调用xPath.evaulate都会实例化一个新的InputSource StringReader xmlReader = new StringReader(xml); InputSource source = new InputSource(xmlReader); XPathExpression xpe = xpath.compile("msg/element/@attrib
xPath.evaulate
都会实例化一个新的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);
现在,我想深入研究我的XML消息,并评估更多信息。为此,我发现自己需要另一次实例化源代码。这是必需的吗?如果我不这样做,我会得到流关闭异常。将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));
XPath=XPathFactory.newInstance()
.newXPath();
InputSource xml=新的InputSource(新的StringReader(“”);
Node root=(Node)xpath.evaluate(“/”,xml,XPathConstants.Node);
System.out.println(xpath.evaluate(“/xml/@foo”,root));
这样可以避免多次解析字符串
如果必须对不同的XML字符串重复使用
InputSource
,则可能可以对不同的读取器实例使用。请详细说明“这可以避免多次解析字符串”?我不明白,您的解决方案也没有使用XPathExpression类。另外,你能帮我回答下面的帖子吗?