Parsing an XML from java

Sreejith22
Sreejith22 used Ask the Experts™
on
Hi experts,

I have been trying to parse this xml structure in the most efficient way I can. Since I am a newbie to XML parsing, I doubt I end up in solutions which are not the best that I could have. Still, I keep trying.

This XML will grow bigger in future, in the same format. Keeping this future enlargement aspect of the xml, can someone kindly suggest a fast mechanism using which I can parse this using SAX parser(or Pull parser?)

I am also unsure that whether the XML structure I have is the best one.

Someone already suggested me "processing that consumes the XML will be easier if you have a perfect one-to-one relationship between request and response(tags)." . So, kindly feel free to modify the XML structure, if one feel that that it will ease processing and the result is achieved quicker.



Any help in this regard which would help me with a proper solution, preferably with code snippet using which I would be able to achieve the output given, is much appreciated, surely.

<root>
  <response value="OK">
    <request>
      <token>Dark</token>
      <token>Night</token>
    </request>
 </response>
 <response value="Done">
    <request>
      <token>Closer</token>
      <token>Zoom in</token>
    </request>
 </response>
</root>

Open in new window


Output required(during for loop iterations):
//During first iteration in for loop
String[] requests = {"Dark", "Night"};
String[] response = {"OK"};
-----------------------------------------------
//During second iteration in for loop
String[] requests = {"Closer", "Zoom in"};
String[] response = {"Done"};

Open in new window


Regards,
Sree
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
My advice would be don;t use anything that requires xpath if performance is important.
The fastest way I have found is to use a TreeWalker to walk the entire tree just once and store what you need in pojos - it looks like that is what you are doing, building up String arrays - they will be very fast, much faster than querying the xml over and over each time.

Here's some sample code on TreeWalker.
http://www.ibm.com/developerworks/xml/library/x-tiptreewlk/index.html
As it is an evergrowing XML document, it is better to use SAX parser which gives you the best performance for parsing large XML documents.
Implemented using SAX parser which was available in android. Had to spent some time implementing it as I was a newbie in xml parsing. Was looking for snippets here.

Author

Commented:
Did the implementation myself after going through different examples provided by developers in different forums.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial