如何解析dom解析器中的空标记以使用php-webservice



在我的xml中可以有像</title>这样的空标记。

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

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

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

有问题的线路是什么?

是这条线吗?

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

对于解析,您可以使用。。。

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

最新更新