2012-09-13 42 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);