0

I am in a confusion that can you help me out this question i.e., I am directly reading xml message using xpath and reading values from it and also i am trying to convert xml to json and reading values because of light weight object so which one is best approach to read values. I am attaching following snippet code.

Below is the code to read values from xml

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String eventNumber = xpath.evaluate("/event/eventnumber", document);

Below is to convert xml to json

JSONObject xmlJSONObj = XML.toJSONObject(xml1);
Vskiran
  • 69
  • 2
  • 8

3 Answers3

0

This really depends on what you will be using the data for. If you need to do a lot of parsing/traversing through the data, JSON is much faster due to the nature of JSON APIs. So in the case that you will be needing to do a lot of data extraction/examination on a single file, I would convert the XML to JSON.

If you only need to find a single field in the XML file or only do a small amount of parsing/data extraction, I would stick to XML. It is not worth the extra processing of converting an XML file to JSON if you are only going to do a small amount of traversing through the XML file. The processing time it takes to convert the XML to JSON and then traverse the JSON is more costly than the processing time it takes to traverse through the XML file once.

  • 1
    @Vskiran 100 values isn't so much, but if you want speed, I would consider CSV if it suits your data. – Peter Lawrey Sep 30 '14 at 08:07
  • If you're finding that you are having to do a lot of traversing through the XML tree, then I would convert to JSON. However, if the elements you are looking for are very shallow and don't require many lines of code to extract the data you need, I would leave it as is. Here's a more in-depth analysis of XML vs. JSON http://stackoverflow.com/questions/3536893/what-are-the-pros-and-cons-of-xml-and-json. A lot of it comes down to preference and usability/readability. – Daniel Hipke Sep 30 '14 at 08:11
0

Another discussion that was published here: JSON and XML comparison

Bottom line in my humble opinion since you receive the message in XML it won't increase efficient to convert it to JSON and then parse it - so stick to XML

Community
  • 1
  • 1
JustinB
  • 311
  • 3
  • 6
0

With your input being XML, converting to JSON for the sake of speed looks like no good idea. I guess, with your other approach, you're losing time on the DOM creation and then even much more on xpath. The fastest solution is IMHO a SAX parser. It creates no objects and only calls you on events you're interested in.

maaartinus
  • 44,714
  • 32
  • 161
  • 320