Parse XML Simple String using Java XPath

You can’t reuse the same InputSource for multiple evaluate() invocations because it’s automatically closed. Hence you’re getting the Stream closed IO exception. Try this

InputSource source1 = new InputSource(new StringReader(xml));
InputSource source2 = new InputSource(new StringReader(xml));

String msg = xpath.evaluate("/resp/msg", source1);
String status = xpath.evaluate("/resp/status", source2);

System.out.println("msg=" + msg + ";" + "status=" + status);

EDIT:
A better approach would be to use a DocumentBuilderFactory to parse your XML and build a Document first (using JAXP’s DOM APIs) which can then be reused across several XPath evaluations.

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);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)