Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an XML file with Java?

Tags:

java

xml

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?

like image 757
Yatendra Avatar asked Feb 25 '10 11:02

Yatendra


2 Answers

I like jdom:

SAXBuilder parser = new SAXBuilder();
Document docConfig = parser.build("config.xml");
Element elConfig = docConfig.getRootElement();
String host = elConfig.getChildText("host");
like image 195
Llistes Sugra Avatar answered Sep 30 '22 06:09

Llistes Sugra


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)

like image 45
Bozho Avatar answered Sep 30 '22 06:09

Bozho