What Is the Best/Simplest Way to Read in an Xml File in Java Application

What is the best/simplest way to read in an XML file in Java application?

There are of course a lot of good solutions based on what you need. If it is just configuration, you should have a look at Jakarta commons-configuration and commons-digester.

You could always use the standard JDK method of getting a document :

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

[...]

File file = new File("some/path");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);

Best way to read XML in Java

dom4j and jdom are pretty easy to use (ignoring the requirement "best" for a moment ;) )

reading data using JAVA from XML files

One of the simplest ways to do it is to use a DOM (Document Object Model) parser. It will load your xml document in memory and turns it into a tree made of Nodes so that you can travers it being able to get the information of any node at any position. It is memory consumming and is generally less prefered than a SAX parser.

Here is an example:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class DomParsing {

public static final String ECB_DATAS ="C:\\xml\\eurofxref-hist-90d.xml";

public static void main(String argv[]) {

try {

File fXmlFile = new File(ECB_DATAS);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("Cube");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("currency : " + eElement.getAttribute("currency") + " and rate is " + eElement.getAttribute("rate"));

}
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

Applied to your file produces the following result:

currency : BGN and rate is 1.9558

Current Element :Cube

currency : CZK and rate is 27.797

Current Element :Cube

currency : DKK and rate is 7.444

How to read and write XML files?

Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>

and the dtd:

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>

First import these:

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;

Here are a few variables you will need:

private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;

Here is a reader (String xml is the name of your xml file):

public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);

Element doc = dom.getDocumentElement();

role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;

} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

return false;
}

And here a writer:

public void saveToXML(String xml) {
Document dom;
Element e = null;

// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();

// create the root element
Element rootEle = dom.createElement("roles");

// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);

e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);

e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);

e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);

dom.appendChild(rootEle);

try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));

} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}

getTextValue is here:

private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}

Add a few accessors and mutators and you are done!

Fastest and optimized way to read the xml

Using ReadAndPrintXMLFileWithStAX below, when I compare with ReadAndPrintXMLFileWithSAX from the answer given by gontard the StAX approach is faster. My test involved running both sample code 500000 times on JDK 1.7.0_07 for the Mac.

ReadAndPrintXMLFileWithStAX:  103 seconds
ReadAndPrintXMLFileWithSAX: 125 seconds

ReadAndPrintXMLFileWithStAX (using Java SE 7)

Below is a more optimized StAX (JSR-173) example using XMLStreamReader instead of XMLEventReader.

import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.stream.*;

public class ReadAndPrintXMLFileWithStAX {

public static void main(String argv[]) throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream("book.xml");
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(in);
streamReader.nextTag(); // Advance to "book" element
streamReader.nextTag(); // Advance to "person" element

int persons = 0;
while (streamReader.hasNext()) {
if (streamReader.isStartElement()) {
switch (streamReader.getLocalName()) {
case "first": {
System.out.print("First Name : ");
System.out.println(streamReader.getElementText());
break;
}
case "last": {
System.out.print("Last Name : ");
System.out.println(streamReader.getElementText());
break;
}
case "age": {
System.out.print("Age : ");
System.out.println(streamReader.getElementText());
break;
}
case "person" : {
persons ++;
}
}
}
streamReader.next();
}
System.out.print(persons);
System.out.println(" persons");
}

}

Output

First Name : Kiran
Last Name : Pai
Age : 22
First Name : Bill
Last Name : Gates
Age : 46
First Name : Steve
Last Name : Jobs
Age : 40
3 persons

How to read an XML file with Java?

Since you want to parse config files, I think commons-configuration would be the best solution.

Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources (including XML)

Is there an easier way to parse XML in Java?

There are two different types of processors for XML in Java (3 actually, but one is weird). What you have is a SAX parser and what you want is a DOM parser. Take a look at http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ for how to use the DOM parser. DOM will create a tree which you can navigate pretty easily. SAX is best for large documents but DOM is much easier if slower and much more memory intensive.

Most efficient way to read and edit an xml file

I've used dom4j when i have wanted to parse xml in Java, and it's quite efficient.



Related Topics



Leave a reply



Submit