Java: Null values parsing XML file

I am trying to parse an xml file to set up the connection of my database. But I got only null strings returned. can someone please check what I am doing wrong?

java Class (Dbconfig is just a Class with Strings of the details)

public class XMLReader {

 public Dbconfig read(){

    Dbconfig conf = new Dbconfig();

    try {
        File file = new File("database.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();
        //System.out.println("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeLst = doc.getElementsByTagName("database");


        Element element = (Element) nodeLst.item(0);
        NodeList url = element.getElementsByTagName("url");
        conf.url = url.item(0).toString();
        NodeList driver = element.getElementsByTagName("driver");
        conf.driver = driver.item(0).toString();
        NodeList username = element.getElementsByTagName("username");
        conf.username = username.item(0).toString();
        NodeList password = element.getElementsByTagName("password");
        conf.password = password.item(0).toString();

        System.out.format("####Printing XML configuration:%s %s %s %s n",conf.url, conf.driver, conf.username, conf.password);


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

the XML file (it should just provide the configuration for 1 database):

<?xml version="1.0" encoding="UTF-8"?>
<database>
    <url>jdbc:mysql://localhost:3306/db</url>
    <driver>com.mysql.jdbc.Driver</driver>
    <username>admin</username>
    <password>admin</password>
</database>

output is:

####Printing XML configuration:[url: null] [driver: null] [username: null] [password: null] 

Answer

change your code as

            Element database = (Element) doc.getElementsByTagName("database").item(0);
            String url = ((Element)database.getElementsByTagName("url").item(0)).getTextContent();
            String driver = ((Element)database.getElementsByTagName("driver").item(0)).getTextContent();
...

or make a method

private static String getParameter(Element database, String paramName) {
    return ((Element)database.getElementsByTagName(paramName).item(0)).getTextContent();
}

Leave a Reply

Your email address will not be published. Required fields are marked *