XMl解析中的空指针异常
我需要解析一个Xml文档并将值存储在文本文件中,当我解析普通数据(如果所有标签都包含数据)时,它的工作状况很好,但是如果任何标签中都没有数据,则它会抛出“
NullpointerException”这样做,为避免出现异常" title="空指针异常">空指针异常,请使用示例代码Sample 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));
}
以上是 XMl解析中的空指针异常 的全部内容, 来源链接: utcz.com/qa/414171.html