2013-12-22 28 views
0

我在XML文件中的以下基本上我试图改变XML文档解析XML文档用java的DocumentBuilder

<?xml version="1.0" encoding="UTF-8"?> 
<configuration> 
    <root level="DEBUG"> 
    </root> 
</configuration> 

的属性这是我的java文件

public static void changeXMLLogLevel(String pathToXMLDocument, String newWarnLevel){ 
    // make sure that xml file is present 
    File f = new File(pathToXMLDocument); 

    if (f.exists()) { 
     try { 
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 
      Document doc = docBuilder.parse(pathToXMLDocument); 


      // Get the warn level 
      Node warnLevel = doc.getElementsByTagName("root").item(0); 

      System.out.println("The warn level is: " + warnLevel); 

      // more code.................. 

对于某些原因警告级别为空,尽管我在我的xml文档中有一个名为root的标签。

这是我得到我的输出 The warn level is: [root: null]

回答

2

我想你误解了你的输出。有了这个

Node warnLevel = doc.getElementsByTagName("root").item(0); 

你在你的xml中得到单一的root标记。该对象的toString()是标记的名称和节点的值,但显然是it always returns null for element nodes

你想要的是获得属性level

Node warnLevel = doc.getElementsByTagName("root").item(0).getAttributes().getNamedItem("level"); 
System.out.println("The warn level is: " + warnLevel); 

它打印

level="DEBUG"