我正在从XML文件读取特定信息。我在尝试读取某些元素(例如DataDate)时遇到问题。我收到了NullPointerException。我认为这是因为在XML文件中有两个带有单词“ Project”的节点,而第一个没有DataDate。
我不知道如何解决此错误。
这是我正在阅读的XML文件的一部分:
package testReadXML;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class TestReadXML {
public static void main(String[] args) {
try {
File xmlFile = new File("C:/Users/diani/Downloads/XML Files/CS01.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element:" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Project");
for (int i = 0; i < nList.getLength(); i ++) {
Node nNode = nList.item(i);
System.out.println("\n" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Object Id : " + eElement.getAttribute("ObjectId"));
System.out.println("Id : " + eElement.getElementsByTagName("Id").item(0).getTextContent());
System.out.println("Name : " + eElement.getElementsByTagName("Name").item(0).getTextContent());
System.out.println("Data Date : " + eElement.getElementsByTagName("DataDate").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
在获取元素时只需添加此If条件
if(eElement.getElementsByTagName("DataDate").getLength() > 0) {
System.out.println("Object Id : " + eElement.getAttribute("ObjectId"));
System.out.println("Id : " + eElement.getElementsByTagName("Id").item(0).getTextContent());
System.out.println("Name : " + eElement.getElementsByTagName("Name").item(0).getTextContent());
System.out.println("Data Date : " + eElement.getElementsByTagName("DataDate").item(0).getTextContent());
}