所以我有很多的麻煩閱讀這個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值時發生異常。
'<! - 這個版本的Eclipse不到風度支持直接創建XML文件 - >'我覺得很難相信。它是什麼版本? – 2013-04-29 02:55:25