读书人

关于xml中出现子节点空指针错误

发布时间: 2012-11-19 10:18:51 作者: rapoo

关于xml中出现子节点空指针异常

??Node[]childNode = new Node[2];
??? db=dbf.newDocumentBuilder();
???File file= null;
???int tempNum=0;
???file = new File("f://a.xml");
???????? try {
????Document dc=db.parse(file);
????NodeList nodeList = dc.getElementsByTagName("configure");
????NodeList childNodes = nodeList.item(0).getChildNodes();
????System.out.println(childNodes.item(1).getFirstChild().getNodeValue().toString());
????for (int j = 0; j < childNodes.getLength(); j++) {
?????Node temp = childNodes.item(j);
?????if (temp instanceof Element) {//如果该地方不用这个判断,那么会出现空指针,
?????
??????childNode[tempNum] = temp.getFirstChild();
????????System.out.println(childNode[tempNum].getNodeValue());
??????tempNum++;
?????}else{
??????System.out.println(temp.getNodeName());
?????}
????}

问题:通过nodeList.item(0).getChildNodes();获得的子节点中如果xml文件中包含空格、换行就会出现异常,因为子节点将会包含该值,因此会出现不符合自己的要求。

解决方法:1.通过?if (temp instanceof Element)过滤掉。

???????????????2.在创建xml时后根据 OutputFormat of=new OutputFormat(,"UTF-8",false):将其该为false就可以实现格式的不分行。

读书人网 >XML SOAP

热点推荐