尝试解析xml文件时出现NullPointerException

时间:2012-09-25 11:15:30

标签: java xml-parsing

我有以下内容:

public static void main(String args[]) {

     // upload config' data for program - param' are path and Xml's Root node/ where to get data from
     confLoader conf = new confLoader("conf.xml", "config"); 

     System.out.println(conf.getDbElement("dataSource") );
     System.out.println(conf.getDbElement("dataSource") );
     System.out.println(conf.getDbElement("dataSource") );  // Fails 
...

负责构建DOM并从('getDbElement()')解析的代码:

public class confLoader{

 DocumentBuilderFactory docBuilderFactory;
 DocumentBuilder docBuilder;
 Document doc;
 NodeList nList;

 public confLoader(String path, String XmlRoot){

    try {
            docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docBuilderFactory.newDocumentBuilder();
            doc = docBuilder.parse(new File(path));
            // normalize text representation
            doc.getDocumentElement().normalize();                
    nList = doc.getElementsByTagName(XmlRoot);

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

public String getDbElement(String element) {

    Node nNode = nList.item(0); //  1st item/node - sql
    try {
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {     /////  Line 36 - Problematic

            Element eElement = (Element) nNode;
            return (((Node) eElement.getElementsByTagName(element).item(0).getChildNodes().item(0)).getNodeValue());
        }
    } catch (Exception ex) {
        System.out.println("Error retrieving " + element + " :" + ex.getMessage());//Thread.dumpStack();
         ex.printStackTrace();
      }
    return "not available";
 }

}

给定代码的stacktrace:

  jdbc:mysql://localhost:...
  java.lang.NullPointerException
  jdbc:mysql://localhost:...
  Error retrieving dataSource :null
  not available
  at exercise.confLoader.getDbElement(confLoader.java:36)
  at exercise.Exercise.main(Exercise.java:22)

      Line 36 : if (nNode.getNodeType() == Node.ELEMENT_NODE)

xml解析完成两次,第三次尝试从Xml解析,我得到NullPointerException。

2 个答案:

答案 0 :(得分:2)

代码太多了!此外,按需阅读配置文件并不是很有用。依赖实例变量会使您的代码更难以测试和理解,甚至在并发场景中可能不安全。您不需要所有这些类,方法和事物。这只是一个问题

public class Exercise {

    public static void main(String[] args) throws XPathExpressionException {

        XPath xpath = XPathFactory.newInstance().newXPath();
        InputSource in = new InputSource("res/config.xml");

        String user = xpath.evaluate("//sql/user/text()", in);
        String password = xpath.evaluate("//sql/password/text()", in);
        String path = xpath.evaluate("//sql/dataSource/text()", in);

        Sql sql = new Sql(path, user, password);
    }

}

您可以选择将所有配置存储在Map<String, String>中,从而使代码更加复杂,但实际上您最好使用能够加载Properties的通用API来自XML。

答案 1 :(得分:0)

通过从构建路径中删除gnujaxp.jar解决了问题。