Tutorial :Most effective way to process a string containing XML, in JAVA



Question:

I have a String which contains XML nodes within it, and am seeking to use DOM parsing to process this string to extract node values and store them in local variables.

The XML which is stored in a String variable:

<carGarage>     <car>        <make>Chrysler</make>        <color>Red</color>     </car>     <car>        <make>Musano</make>        <color>Blue</color>     </car>  </carGarage>  

My Java class where I want to extract the XML values and store them in the local attributes:

public class CarGarage  {   String make, color;        public void setMake(String make)      { this.make = make; }        public void setColor(String color)      { this.color = color; }        public void DOMparsingMethod(Node thisNode)      { int typeOfNode = thisNode.getNodeType();        ...      }  }  

What is the best way to approach this? I have looked at StringBufferInputStream but that is deprecated. I am truly quite lost.

Thankyou, Lucas.


Solution:1

Look at using DocumentBuilder to parse from any kind input stream. Here's an example that reads to a class like yours from a file.


Solution:2

There are lots of object-to-xml binding libraries out there which do exactly what you want, but they tend to be rather bulky tools.

For this simple example, handling the dom yourself makes sense. justinhj's suggestion of the built-in java libraries for this is a good start, although this sometimes gets ugly too, since the jdk doesn't usually provide you with an xml parser, requiring you to plug in your own magically behind the scenes.

I tend to prefer jdom for this sort of thing. It's effectively the same as the DocumentBuilder route, but similar and only partly compatible.


Solution:3

Why use DOM?

If you are trying to just read in and turn the xml into an object then I would suggest STAX, as SAX is faster than DOM, but too much coding, STAX is much nicer, and you can learn more about it below. https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/programming-and-development/?p=639


Solution:4

I suggest you look at XStream. It is support conversion of XML into objects. You can give it the XML and it will give you a list of the objects you want.


Solution:5

In my experience DOM is useful for this kind of thing because it has a low learning curve compared to SAX / STAX, even though its not as fast or memory efficient. Once you've got a DOM document, you can use XPath queries against the document to get individual element contents and parse them.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »