在blackberry xml解析中显示空节点的消息

时间:2012-07-14 15:57:35

标签: blackberry xml-parsing nodes

在黑莓应用程序中解析XML结果,该应用程序返回表单中的节点;

<searches> 
<search id ='1234'>
<name> somename </name>
<address> some address </address>
<sector> some sector </sector>
<contacts> 12345, me@me.com </contacts>
<searches>     

当搜索没有任何匹配时,结果返回为空,即;

<name></name>
<address></address>
<sector></sector> 
<contacts></contacts>

不返回结果。它看起来像<searches></searches>。在搜索结果仅返回<searches></searches>

时,如何在这种情况下指定对话框警报

这是我与解析器连接的Http连接。

   try{
         HttpConnection connection = (HttpConnection)Connector.open("http://someurl.xml",Connector.READ_WRITE);
         URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
         postData.append("username", "someusername");
         postData.append("password", "somepassword");
         postData.append("term", word);
         connection.setRequestMethod(HttpConnection.POST);
         connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
         connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
         OutputStream requestOut = connection.openOutputStream();
         requestOut.write(postData.getBytes());
         connection.getHeaderField("Content-type"); 
         DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
         docBuilder.isValidating();
         InputStream detailIn = connection.openInputStream();
         doc = docBuilder.parse(detailIn);
         requestOut.close();
         connection.close(); 
         NodeList list = doc.getElementsByTagName("name");
         NodeList list1 = doc.getElementsByTagName("address");
         NodeList list2 = doc.getElementsByTagName("sector");
         NodeList list3 = doc.getElementsByTagName("contacts");
         callback(list,list1,list2,list3);
         requestOut.close();
         connection.close();
     }
     catch(Exception ex){
         System.out.println(ex.toString());
     } 

我是使用if还是for?

1 个答案:

答案 0 :(得分:1)

我没有在我面前的Eclipse插件(因此我无法测试此代码),但是这样的东西应该可以工作:

doc = docBuilder.parse(detailIn);
requestOut.close();
connection.close(); 
NodeList list = doc.getElementsByTagName("name");
NodeList list1 = doc.getElementsByTagName("address");
NodeList list2 = doc.getElementsByTagName("sector"); 
NodeList list3 = doc.getElementsByTagName("contacts");
if (list == null || list.getLength() == 0) {
    // no results, so post an alert on the UI thread
    UiApplication.getUiApplication().invokeLater(new Runnable() {
        public void run() {
            Dialog.alert("No results found!");
        }
    });
}

这只测试name元素的存在,假设如果缺少name,其他元素(地址,扇区和联系人)也会丢失。如果您的应用程序不适用,您可以选择if语句检查list1list2list3