抱歉,我对Java知之甚少。我被交给了这段代码来接管。基本上,运行代码时,我在String[] patient = {eElement.getElementsByTagName("Name").item(0).getTextContent(), eElement.getElementsByTagName("ID").item(0).getTextContent(), eElement.getElementsByTagName("acquisitionDate").item(0).getTextContent(), eElement.getElementsByTagName("pages").item(0).getTextContent() };的行上得到了NullPointerException。

这是解析XML的块

//parse array of string arrays from xml file that represent the patient list we expect to see, needs to be sorted by acquisition date, in reverse chronological order.
File fxmlFile = new File("patientList.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fxmlFile);

doc.getDocumentElement().normalize(); //should not be necessary but recommended (http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work)

NodeList nList = doc.getElementsByTagName("patient");

String[][] retList = new String[nList.getLength()][4];

for(int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
Element eElement = (Element)nNode;
String[] patient = {eElement.getElementsByTagName("Name").item(0).getTextContent(), eElement.getElementsByTagName("ID").item(0).getTextContent(), eElement.getElementsByTagName("acquisitionDate").item(0).getTextContent(), eElement.getElementsByTagName("pages").item(0).getTextContent() };

retList[i] = patient;
}


这是Improts,不确定是否需要

package test.java.WebReview.Tests;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.Assert;
import main.java.WebReview.Pages.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


这是XML文件

<?xml version="1.0"?>
<patients>
<patient>
<acquisitionDate>2015-04-03T10:03:49.0000000</acquisitionDate>
<id>9876543230</id>
<name>autoTestLast30, autoTestFirst30</name>
<pages>3</pages>
</patient>
</patients>

最佳答案

eElement.getElementsByTagName("Name")


在您的示例中计算为null(并引发异常),请尝试:

eElement.getElementsByTagName("name") //case sensitive!


..这只是“冰山一角”,请注意所有标签名称中的大小写和拼写!

08-27 14:13