0

在我的 xml 中可以有空标签,如</title>.

问题是当我解析 xml 时,当我到达 xml 中的这一行时,我得到了空指针异常。

我应该如何在我的解析文件中检查这样的标签?

ArrayList<String>textcomment = new ArrayList<String>();         
for(int i = 0;i<nl.getLength();i++) 
{   
    Element e = (Element)nl.item(i);
    // crash on this string find first time a value and second time find </no_of_comments> 
    String noOfcomment = e.getElementsByTagName("no_of_comments").item(0).getFirstChild ().getNodeValue(); 
    aryNoOfcomment.add(i, noOfcomment);
}
4

2 回答 2

0

解析你可以使用这个...

FileInputStream fi = new FileInputStream(dir); 
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
doc =  builder.parse(fi);

NodeList nlorgid = doc.getElementsByTagName("Organization");
String orgidfromxml = ((Element)nlorgid.item(0)).getAttribute("id");
System.out.println(" organization id from xml is "+orgidfromxml);
于 2012-09-13T11:09:42.733 回答
0

有什么问题?

是这条线?

String noOfcomment = e.getElementsByTagName ("no_of_comments"). item (0). getFirstChild (). getNodeValue ();

您将所有内容都放在同一行中,因此您不会检查其中一个是否为空。

您可以分开然后检查结果是否为空,如下所示:

List<String> yourList = new ArrayList<String>();
NodeList nl = e.getElementsByTagName ("no_of_comments");
if(nl != null){
    for(int i = 0;i<nl.getLength();i++) 
    {   
        Node n = nl.item(i).getFirstChild();
        if(n!=null){
             String value = n.getNodeValue();
             yourList.add(value);
        }
    }
}
于 2012-09-13T11:17:52.537 回答