2012-09-13 44 views
0

在我的XML可以有像</title>空标签。如何解析空标记从DOM分析器使用PHP的web服务

问题是,当我解析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); 
} 

回答

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); 
     } 
    } 
} 
+0

,以及如何添加字符串值ArrayList中 –

+0

我编辑的代码,就像这样:d –

+0

确定...但先生断点不在这个位置arraylist工作,我可以添加这个ArrayList到阵列..请帮助我先生... –

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);