所以我在阅读这个 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 吗?我现在真的很沮丧。谢谢!
PS你们中的一些人回答了出现异常的行上方的行。当我尝试打印出 secondaryElement 元素中的 testAttribute 值时,会发生异常。