2013-04-29 44 views
0

所以我有很多的麻烦阅读这个XML文件:在Java中读取XML文件时遇到问题?

<?xml version = "1.0" encoding = "UTF-8"?> 
<!--this version of Eclipse dosn't support direct creation of XML files--> 
<!-- you have to create one in notepad and then copy/paste it into Eclipse--> 

<root testAttribute = "testValue"> 
    <data>Phoebe</data> 
    <data>is</data> 
    <data>a</data> 
    <data>puppy!</data> 

    <secondElement testAttribute = "testValueAgain"> 
     <data2>Poop</data2> 
     <data2>Doopy</data2> 
    </secondElement> 
</root> 

在我的Java文件,我得到了这一条线一个NullPointerException。 下面的代码:(我要指出哪里发生异常时)

import javax.xml.parsers.*; 
import org.w3c.dom.*; 
import org.xml.sax.*; 

import java.io.*; 

public class Reading { 
    public static void main(String args[]){ 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     try { 
      DocumentBuilder builder = factory.newDocumentBuilder(); 
      Document doc = builder.parse(new File("res/Test.xml")); 

      ////////////////////GET ELEMENTS////////////////// 

      Element rootElement = doc.getDocumentElement(); 
      System.out.println("Root element: " + doc.getDocumentElement().getNodeName()); 
      System.out.println("testAttribute for root element: " 
       + rootElement.getAttribute("testAttribute")); 

      Element secondElement = doc.getElementById("secondElement"); 
      System.out.println("testAttribute for second element: " + 
       secondElement.getAttribute("testAttribute")); //THIS IS THE LINE 

      NodeList list = rootElement.getElementsByTagName("data"); 

      NodeList list2 = rootElement.getElementsByTagName("data2"); 

      ////////////////////////////////// 

      for(int i = 0; i < list.getLength(); i++){ 
       Node dataNode = list.item(i); 
       System.out.println("list index: " + i + " data at that index: " + 
       dataNode.getTextContent()); 
      } 

      for(int i = 0; i < list2.getLength(); i++){ 
       Node dataNode = list2.item(i); 
       System.out.println("list2 index: " + i + " data at that index: " + 
       dataNode.getTextContent()); 
      } 
     }catch(ParserConfigurationException e){ 
      e.printStackTrace(); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     }catch(SAXException e){ 
      e.printStackTrace(); 
     } 
    } 
} 

你们可以看看我的代码,并告诉我,我能做些什么,以避免NullPointerException异常?我现在很沮丧。谢谢!

P.S.你们中的一些人回答了有异常的线路上方的线路。当我尝试PRINT OUT secondaryElement元素中的testAttribute值时发生异常。

+0

'<! - 这个版本的Eclipse不到风度支持直接创建XML文件 - >'我觉得很难相信。它是什么版本? – 2013-04-29 02:55:25

回答

1

getElementByID不是你认为的那样,因此返回null(没有id =“...”属性)。

1

快速回答是您的secondElement为空。原因是因为你没有id="secondElement"的元素。您的代码预计文档包含类似

<myelement id="secondElement">...</myelement>