我一直在研究这个问题很长一段时间,但无法弄清楚。有一个给定的“XML”文件,该文件需要被解析并在屏幕上显示:解析Java中的假xml文件
<office>
<name>joe</name>
<surname>smith</surname>
<name>bob</name>
<surname>black</surname>
.....
</office>
我发现就行代码的一些伟大的样品,但他们似乎没有一个XML文件,该文件工作没有正确设置为这个,所以如果我添加一个标签,我可以让我的代码工作,但问题是我无法对“xml”文件进行任何更改。
这是我在这里找到的其他人的代码已被修改。
这里是我的代码以MODS:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ReadAndPrintXMLFile{
public static void main (String argv []) throws ParserConfigurationException, SAXException, IOException{
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("office.xml"));
// normalize text representation
doc.getDocumentElement().normalize();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName() + "\n");
//counts how many times <name> is found in the file
//then the number is used in the for loop below
NodeList listOfTerms = doc.getElementsByTagName("name");
int totalTerms = listOfTerms.getLength();
System.out.println("Total no of terms : " + totalTerms + "\n");
for(int s= 0; s<listOfTerms.getLength() ; s++){
Node firstTermNode = listOfTerms.item(s);
if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){
Element firstTermElement = (Element)firstTermNode;
//-------
NodeList firstWordList = firstTermElement.getElementsByTagName("name");
Element firstWordElement = (Element)firstWordList.item(0);
NodeList textWordList = firstWordElement.getChildNodes();
System.out.println("Name : " +
((Node)textWordList.item(0)).getNodeValue().trim());
//-------
NodeList defList = firstTermElement.getElementsByTagName("surname");
Element defElement = (Element)defList.item(0);
NodeList textDefList = defElement.getChildNodes();
System.out.println("Surname : " +
((Node)textDefList.item(0)).getNodeValue().trim());
}//end of if clause
}//end of for loop with s var
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
}catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
}catch (Throwable t) {
t.printStackTrace();
}
//System.exit (0);
}//end of main
}
该错误消息我得到的是这样的:
java.lang.NullPointerException
at Data.main(Data.java:45) //maybe a different line in the code for you.
如果我使用文档的根计数器它打印的结果一次,某些原因getChildNodes()无法正常工作。
您是否尝试调试代码?至少说出哪一行是#45。 – AlexR
@Bart,是的,我试图调试它。这是一行:NodeList textWordList = firstWordElement.getChildNodes();该错误是指。 – arubin