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

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


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);


XML Code:

<?xml version="1.0"?><company>    <staff id="1001">        <firstname>yong</firstname>        <lastname>mook kim</lastname>        <nickname>mkyong</nickname>        <salary>100000</salary>    </staff>    <staff id="2001">        <firstname>low</firstname>        <lastname>yin fong</lastname>        <nickname>fong fong</nickname>        <salary>200000</salary>    </staff></company>

Java Code:

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 ReadXMLFile {  public static void main(String argv[]) {    try {    File fXmlFile = new File("/Users/mkyong/staff.xml");    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("staff");    System.out.println("----------------------------");    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("Staff id : "                               + eElement.getAttribute("id"));            System.out.println("First Name : "                               + eElement.getElementsByTagName("firstname")                                 .item(0).getTextContent());            System.out.println("Last Name : "                               + eElement.getElementsByTagName("lastname")                                 .item(0).getTextContent());            System.out.println("Nick Name : "                               + eElement.getElementsByTagName("nickname")                                 .item(0).getTextContent());            System.out.println("Salary : "                               + eElement.getElementsByTagName("salary")                                 .item(0).getTextContent());        }    }    } catch (Exception e) {    e.printStackTrace();    }  }}

Output:

----------------Root element :company----------------------------Current Element :staffStaff id : 1001First Name : yongLast Name : mook kimNick Name : mkyongSalary : 100000Current Element :staffStaff id : 2001First Name : lowLast Name : yin fongNick Name : fong fongSalary : 200000

I recommended you reading this: Normalization in DOM parsing with java - how does it work?

Example source.


Is there a particular reason you have chosen XML config files? I have done XML configs in the past, and they have often turned out to be more of a headache than anything else.

I guess the real question is whether using something like the Preferences API might work better in your situation.

Reasons to use the Preferences API over a roll-your-own XML solution:

  • Avoids typical XML ugliness (DocumentFactory, etc), along with avoiding 3rd party libraries to provide the XML backend

  • Built in support for default values (no special handling required for missing/corrupt/invalid entries)

  • No need to sanitize values for XML storage (CDATA wrapping, etc)

  • Guaranteed status of the backing store (no need to constantly write XML out to disk)

  • Backing store is configurable (file on disk, LDAP, etc.)

  • Multi-threaded access to all preferences for free