Saturday, 10 January 2015

Parsing an XML file with DOM in Java

Below program describes that, reading the data from network xml resource. And it describe how to get particular  node value and display it in console.

In java we have by default javax.xml library which contains the several class to manage the Document Object Model (xml) data. But it is too lengthy. By using the third party libraries such as JDOM etc we can manage the xml content very easily.


package files;

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadXML {

public static void main(String[] args) {

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse("http://services.explorecalifornia.org/rss/tours.php");
NodeList nodeList = doc.getElementsByTagName("title");

System.out.println("Total elements " +nodeList.getLength()+" are presented");

for (int i = 0; i < nodeList.getLength(); i++) {

Element item = (Element)nodeList.item(i);

System.out.println(item.getFirstChild().getNodeValue());

}
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (DOMException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

No comments:

Post a Comment