解析XML数据意外失败

时间:2011-04-25 02:35:03

标签: android xml textview

我目前正在尝试使用动态解析xml中的数据。所以我试图通过不同的标签检索数据,并使用SimpleAdapter将它们插入到不同的文本视图中。但是在我看来它失败了,它应该起作用。请帮我解决这个问题。

这是我的 SearchResults.java

public class SearchResult extends ListActivity{

String set_number;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    //retrieve text passed from previous activity
    Bundle bundle = getIntent().getExtras();
    String searchItems = bundle.getString("searchItems");

    //get the xml data using retrieve text from previous activity      
    String xmlSetNo = XMLFunctions.getSetNoXML(searchItems);
    Document docSetNo = XMLFunctions.XMLfromString(xmlSetNo);//change xml data to doc format

    NodeList nodeSetNo = docSetNo.getElementsByTagName("find");

    for (int i = 0; i < nodeSetNo.getLength(); i++) {                           
        Element e = (Element)nodeSetNo.item(i);
        set_number = XMLFunctions.getValue(e, "set_number");
    }       

    String xmlRecords = XMLFunctions.getRecordsXML(set_number);
    Document docRecords = XMLFunctions.XMLfromString(xmlRecords);

    NodeList nodeRecords = docRecords.getElementsByTagName("metadata");

    for(int i = 0; i < nodeRecords.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();    

        Element e = (Element)nodeRecords.item(i);

        //map.put("cover_image", getTagValue("varfield id='20'", e));
        map.put("title", getTagValue("varfield id='245'", e));
        map.put("author", getTagValue("varfield id='100'", e));
        map.put("format", getTagValue("fixfield id='FMT'", e));
        map.put("call_number", getTagValue("varfield id='099'", e));
        /*
        map.put("set_number", XMLFunctions.getValue(e, "set_number"));
        map.put("no_records", "No. of Records:" + XMLFunctions.getValue(e, "no_records"));
        map.put("no_entries", "No. of Entries: " + XMLFunctions.getValue(e, "no_entries"));
        mylist.add(map);
        */
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.search_result_display_list, 
                    new String[] { "cover_image","title","author","format","call_number"}, 
                    new int[] {R.id.cover_image, R.id.item_title, R.id.item_author,R.id.item_format,R.id.item_call_number });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);  
    /*lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
            Toast.makeText(SearchResult.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

        }
    });*/
}

 private static String getTagValue(String sTag, Element eElement){
        NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0); 

        return nValue.getNodeValue();    
     }
}

这是我的 XMLFunctions.java ,我解析了我的xml数据:

public class XMLFunctions {

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}

/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 public static String getSetNoXML(String searchItems){   
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            //request for item's set_number
            HttpGet requestSetNumber = new HttpGet("http://spark.opac.tp.edu.sg/X?op=find&scan_code=find_wrd&request="+ searchItems +"&base=tpl01");

            HttpResponse httpResponse = httpClient.execute(requestSetNumber);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<find status=\"error\"><msg>Can't connect to server</msg></find>";
        } catch (MalformedURLException e) {
            line = "<find status=\"error\"><msg>Can't connect to server</msg></find>";
        } catch (IOException e) {
            line = "<find status=\"error\"><msg>Can't connect to server</msg></find>";
        }
        return line;
}

 public static String getRecordsXML(String setNumber){   
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            //request records via set_number
            HttpGet requestRecords = new HttpGet("http://spark.opac.tp.edu.sg/X?op=present&set_no="+ setNumber +"&set_entry=000000001,000000002,000000003," +
                    "000000004,000000005,000000006,000000007,000000008,000000009,000000010&format=marc");


            HttpResponse httpResponse = httpClient.execute(requestRecords);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<find status=\"error\"><msg>Can't connect to server</msg></find>";
        } catch (MalformedURLException e) {
            line = "<find status=\"error\"><msg>Can't connect to server</msg></find>";
        } catch (IOException e) {
            line = "<find status=\"error\"><msg>Can't connect to server</msg></find>";
        }
        return line;
}

public static int numResults(Document doc){     
    Node results = doc.getDocumentElement();
    int res = -1;

    try{
        res = Integer.valueOf(results.getAttributes().getNamedItem("find").getNodeValue());
    }catch(Exception e ){
        res = -1;
    }

    return res;
}

public static String getValue(Element item, String str) {       
    NodeList n = item.getElementsByTagName(str);        
    return XMLFunctions.getElementValue(n.item(0));
}
}

最后,这是 LogCat 的输出:

  

04-25 10:20:15.932:ERROR / AndroidRuntime(418):致命异常:主要
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):java.lang.RuntimeException:无法启动活动ComponentInfo {joel.TPLibrary / joel.TPLibrary.SearchResult}:java.lang.NullPointerException
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.access $ 2300(ActivityThread.java:125)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2033)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.os.Handler.dispatchMessage(Handler.java:99)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.os.Looper.loop(Looper.java:123)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.main(ActivityThread.java:4627)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):at java.lang.reflect.Method.invokeNative(Native Method)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):at java.lang.reflect.Method.invoke(Method.java:521)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)   04-25 10:20:15.932:ERROR / AndroidRuntime(418):at dalvik.system.NativeStart.main(Native Method)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):引起:java.lang.NullPointerException    04-25 10:20:15.932:ERROR / AndroidRuntime(418):at joel.TPLibrary.SearchResult.getTagValue(SearchResult.java:89)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):at joel.TPLibrary.SearchResult.onCreate(SearchResult.java:58)

  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
  04-25 10:20:15.932:ERROR / AndroidRuntime(418):... 11更多

1 个答案:

答案 0 :(得分:1)

我认为你要以错误的方式在android中解析XML。坦率地说,代码看起来比它需要的更加混乱。

相反,我建议使用名为Simple的基于注释的XML框架,它将帮助您轻松编写和输出XML:我非常喜欢I even wrote a blog post about how to include it in your Android projects

如果您提供一些示例XML,那么我可以为您提供有关出错的更多信息。