9

I don't need to read complex XML files. I just want to read the following configuration file with a simplest XML reader

<config>
    <db-host>localhost</db-host>
    <db-port>3306</db-port>
    <db-username>root</db-username>
    <db-password>root</db-password>
    <db-name>cash</db-name>
</config>

How to read the above XML file with a XML reader through Java?

Community
  • 1
  • 1
Amit
  • 33,847
  • 91
  • 226
  • 299
  • 1
    As these are name value pairs, why not just define this as a .properties file? That way you don't need to parse it at all. – Adamski Feb 25 '10 at 11:51
  • 1
    possible duplicate of [What is the best/simplest way to read in an XML file in Java application?](http://stackoverflow.com/questions/428073/what-is-the-best-simplest-way-to-read-in-an-xml-file-in-java-application) – ripper234 May 12 '10 at 11:00

9 Answers9

10

I like jdom:

SAXBuilder parser = new SAXBuilder();
Document docConfig = parser.build("config.xml");
Element elConfig = docConfig.getRootElement();
String host = elConfig.getChildText("host");
Llistes Sugra
  • 991
  • 4
  • 9
  • 24
8

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)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I tried commons-cofiguration and got one compiler error as shown above in the snapshot... The snapshot may be too unclear due to size reduction so you can access the snapshot at http://i45.tinypic.com/2eamoeg.jpg ............. OR ..... just drag n drop the pic to your browser address bar (if you are using firefox) – Amit Feb 26 '10 at 05:05
  • Yatendra Goel you have to download apache commons-lang as well. And some other commons as well - see here http://commons.apache.org/configuration/dependencies.html – Bozho Feb 26 '10 at 06:18
  • I wrote the following statement but it is not working..... HOST = config.getString("db-host");...................... Is there any mistake in this statement... – Amit Feb 26 '10 at 07:43
  • The above statement is written w.r.t the config.xml shown above. – Amit Feb 26 '10 at 07:43
  • http://commons.apache.org/configuration/userguide/howto_xml.html#Accessing_properties_defined_in_XML_documents see here – Bozho Feb 26 '10 at 08:51
5

You could use a simple DOM parser to read the xml representation.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse("config.xml");
Luhar
  • 1,859
  • 2
  • 16
  • 23
4

If you just need a simple solution that's included with the Java SDK (since 5.0), check out the XPath package. I'm sure others perform better, but this was all I needed. Here's an example:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

...

try {
    XPath xpath = XPathFactory.newInstance().newXPath();
    InputSource inputSource = new InputSource("strings.xml");

    // result will equal "Save My Changes" (see XML below)
    String result = xpath.evaluate("//string", inputSource);
}
catch(XPathExpressionException e) {
    // do something
}

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="saveLabel">Save My Changes</string>
</resources>
Ben Jakuben
  • 3,147
  • 11
  • 62
  • 104
2

There are several XML parsers for Java. One I've used and found particularly developer friendly is JDOM. And by developer friendly, I mean "java oriented" (i.e., you work with objects in your program), instead of "document oriented", as some other tools are.

dariopy
  • 568
  • 1
  • 7
  • 18
2

I would recommend Commons Digester, which allows you to parse a file without writing reams of code. It uses a series of rules to determine what action is should perform when encountering a given element or attribute (a typical rule might be to create a particular business object).

Adamski
  • 54,009
  • 15
  • 113
  • 152
0

For a similar use case in my application I used JaxB. With Jaxb, reading XML files is like interacting with Java POJOs. But to use JAXB you need to have the xsd for this xml file. You can look for more info here

Cshah
  • 5,612
  • 10
  • 33
  • 37
0

If you want to be able to read and write objects to XML directly, you can use XStream

Jorn
  • 20,612
  • 18
  • 79
  • 126
0

Although I have not tried XPath yet as it has just come to my attention now, I have tried a few solutions and have not found anything that works for this scenario.

I decided to make a library that fulfills this need as long as you are working under the assumptions mentioned in the readme. It has the advantage that it uses SAX to parse the entire file and return it to the user in the form of a map so you can lookup values as key -> value.

https://github.com/daaso-consultancy/ConciseXMLParser

If something is missing kindly inform me of the missing item as I only develop it based on the needs of others and myself.

Omar Abdel Bari
  • 934
  • 9
  • 17
  • You're answering a duplicate. Please consider answering the originate thread. – yacc Sep 07 '17 at 16:44
  • @yacc thanks for your comment. However I looked at the reported [potential duplicate](https://stackoverflow.com/questions/428073/what-is-the-best-simplest-way-to-read-in-an-xml-file-in-java-application) and it was not objective in how it was stated ("best/simplest" solution). If there is another post that I have missed, please provide me the link so I can check. However, in this question an XML example was provided and questioner clearly mentions that he wants a solution that requires very few lines of code. This is why I have replied to this. – Omar Abdel Bari Sep 07 '17 at 17:43