我需要解析一个 Xml 文档并将值存储在文本文件中,当我解析普通数据时(如果所有标签都有数据)那么它工作正常,但如果任何标签没有数据那么它会抛出空指针异常"我需要做什么,以避免空指针异常,请用示例代码建议我示例 xml:
I need to parser an Xml Document and store the values in Text File, when i am parsing normal data (If all tags have data) then its working fine, but if any tag doesnt have data then it throwing "Null pointerException" what i need to do, to avoid null pointer exception, please suggest me with sample codes 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 解析中的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!