我想遍历一段 XML 打印中的所有元素。我的问题是我在staff1
标签之后不断收到一个空指针异常,即john 465456433 gmail1 area1 city1
这是我的 Java 代码,用于打印 xml 文件中的所有元素:
File fXmlFile = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("*");
System.out.println("----------------------------");
Node n=null;
Element eElement=null;
for (int i = 0; i < nList.getLength(); i++) {
System.out.println(nList.getLength());
n= nList.item(i);
System.out.println("\nCurrent Element :" + n.getNodeName());
if (n.getNodeType() == Node.ELEMENT_NODE) {
eElement = (Element) n.getChildNodes();
System.out.println("\nCurrent Element :" + n.getNodeName());
name = eElement.getElementsByTagName("name").item(i).getTextContent(); //here throws null pointer exception after printing staff1 tag
phone = eElement.getElementsByTagName("phone").item(i).getTextContent();
email = eElement.getElementsByTagName("email").item(i).getTextContent();
area = eElement.getElementsByTagName("area").item(i).getTextContent();
city = eElement.getElementsByTagName("city").item(i).getTextContent();
}
n.getNextSibling();
}
XML 文件:
<?xml version="1.0"?>
<company>
<staff1>
<name>john</name>
<phone>465456433</phone>
<email>gmail1</email>
<area>area1</area>
<city>city1</city>
</staff1>
<staff2>
<name>mary</name>
<phone>4655556433</phone>
<email>gmail2</email>
<area>area2</area>
<city>city2</city>
</staff2>
<staff3>
<name>furvi</name>
<phone>4655433</phone>
<email>gmail3</email>
<area>area3</area>
<city>city3</city>
</staff3>
</company>
预期输出:
john
465456433
gmail1
area1
city1
mary
4655556433
gmail2
area2
city2
furvi
4655433
gmail3
area3
city3