Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java:XML Parser

Tags:

java

xml

I have a response XML something like this -

<Response> <aa> <Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> </aa> </Response>

I want to extract the whole content from <Fromhere> to </Fromhere> in a string. Is it possible to do that through any string function or through XML parser?

Please advice.

like image 571
Pavan Avatar asked Feb 28 '23 11:02

Pavan


1 Answers

You could try an XPath approach for simpleness in XML parsing:

InputStream response = new ByteArrayInputStream("<Response> <aa> "
        + "<Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> "
        + "</aa> </Response>".getBytes()); /* Or whatever. */

DocumentBuilder builder = DocumentBuilderFactory
        .newInstance().newDocumentBuilder();
Document doc = builder.parse(response);

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("string(/Response/aa/FromHere)");
String result = (String)expr.evaluate(doc, XPathConstants.STRING);

Note that I haven't tried this code. It may need tweaking.

like image 71
izb Avatar answered Mar 07 '23 00:03

izb