gpt4 book ai didi

java - XMl解析中的空指针异常

转载 作者:数据小太阳 更新时间:2023-10-29 02:24:25 24 4
gpt4 key购买 nike

我需要解析一个 Xml 文档并将值存储在文本文件中,当我解析普通数据时(如果所有标签都有数据)那么它工作正常,但是如果任何标签没有数据然后它抛出“Null pointerException”我需要做什么,以避免空指针异常,请给我建议示例代码示例 xml:

<company>
<staff>
<firstname>John</firstname>
<lastname>Kaith</lastname>
<nickname>Jho</nickname>
<Department>Sales Manager</Department>
</staff>
<staff>
<firstname>Sharon</firstname>
<lastname>Eunis</lastname>
<nickname></nickname>
<Department></Department>
</staff>
<staff>
<firstname>Shiny</firstname>
<lastname>mack</lastname>
<nickname></nickname>
<Department>SAP Consulting</Department>
</staff>
</company>

代码:

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;
import java.io.File;

public class ReadXMLFile {

public static void main(String argv[]) {

try {

File fXmlFile = new File("c:\\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("staff");
System.out.println("-----------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("Department", eElement));

}
}
} catch (Exception e) {
e.printStackTrace();
}
}

private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

Node nValue = (Node) nlList.item(0);

return nValue.getNodeValue();
}

}

最佳答案

只要检查对象不是null:

private static String getTagValue(String tag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
if(nValue == null)
return null;
return nValue.getNodeValue();
}

String salary = getTagValue("Department", eElement);
if(salary != null) {
System.out.println("Salary : " + getTagValue("Department", eElement));
}

关于java - XMl解析中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11828560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com