0

在一个黑莓应用程序中解析一个 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 ?

4

1 回答 1

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语句 check list1, list2, and list3also。

于 2012-07-14T20:53:04.617 回答