您不能将其重复
InputSource用于多个
evaluate()调用,因为它会自动关闭。因此,您将获得
StreamclosedIO异常。试试这个
InputSource source1 = new InputSource(new StringReader(xml));InputSource source2 = new InputSource(new StringReader(xml));String msg = xpath.evaluate("/resp/msg", source);String status = xpath.evaluate("/resp/status", source2);System.out.println("msg=" + msg + ";" + "status=" + status);编辑:
更好的方法是使用A
documentBuilderFactory解析您的XML并构建
document第一个(使用JAXP的DOM
API),然后可以在多个XPath评估中重复使用。
String xml = "<resp><status>good</status><msg>hi</msg></resp>";InputSource source = new InputSource(new StringReader(xml));documentBuilderFactory dbf = documentBuilderFactory.newInstance();documentBuilder db = dbf.newdocumentBuilder();document document = db.parse(source);XPathFactory xpathFactory = XPathFactory.newInstance();XPath xpath = xpathFactory.newXPath();String msg = xpath.evaluate("/resp/msg", document);String status = xpath.evaluate("/resp/status", document);System.out.println("msg=" + msg + ";" + "status=" + status);


