Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid repeated instantiation of InputSource with XPath in Java

Currently I am parsing XML messages with XPath Expression. It works very well. However I have the following problem:

I am parsing the whole data of the XML, thus I instantiate for every call made to xPath.evaulate a 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);

Now I would like to go deeper into my XML message and evaluate more information. For this I found myself in the need to instantiate source another time. Is this required? If I don't do it, I get Stream closed Exceptions.

like image 744
Konrad Reiche Avatar asked Apr 06 '11 14:04

Konrad Reiche


1 Answers

Parse the XML to a DOM and keep a reference to the node(s). Example:

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

This avoids parsing the string more than once.

If you must reuse the InputSource for a different XML string, you can probably use the setters with a different reader instance.

like image 58
McDowell Avatar answered Oct 21 '22 09:10

McDowell