解析XML数据的意外失败 [英] Parsing XML data fails unexpectedly

查看:73
本文介绍了解析XML数据的意外失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正试图使用​​一个动态解析的XML数据。所以我想通过不同的标签来获取数据,并把它们插入到使用SimpleAdapter不同textviews。但其未能当我的角度来看,它应该工作。请帮我弄清楚了这一点。

这是我的 SearchResults.java

 公共类信息搜索结果扩展ListActivity {

字符串SET_NUMBER;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.list);

    ArrayList的< HashMap的<字符串,字符串>> mylist中=新的ArrayList< HashMap的<字符串,字符串>>();

    //从previous活动检索文本传递
    束束= getIntent()getExtras()。
    串searchItems = bundle.getString(searchItems);

    通过检索previous活动文本XML数据//获取
    字符串xmlSetNo = XMLFunctions.getSetNoXML(searchItems);
    文档docSetNo = XMLFunctions.XMLfromString(xmlSetNo); //改变XML数据,doc格式

    节点列表nodeSetNo = docSetNo.getElementsByTagName(找到);

    的for(int i = 0; I< nodeSetNo.getLength();我++){
        元素e =(元)nodeSetNo.item(我);
        SET_NUMBER = XMLFunctions.getValue(即SET_NUMBER);
    }

    字符串xmlRecords = XMLFunctions.getRecordsXML(SET_NUMBER);
    文档docRecords = XMLFunctions.XMLfromString(xmlRecords);

    节点列表nodeRecords = docRecords.getElementsByTagName(元数据);

    的for(int i = 0; I< nodeRecords.getLength();我++){
        HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();

        元素e =(元)nodeRecords.item(我);

        //map.put("cover_image,getTagValue(varfield ID = '20',E));
        map.put(标题,getTagValue(varfield ID ='245',E));
        map.put(作家,getTagValue(varfield ID ='100',E));
        map.put(格式,getTagValue(fixfield ID ='格式化',E));
        map.put(call_number,getTagValue(varfield ID ='099',E));
        / *
        map.put(SET_NUMBER,XMLFunctions.getValue(即SET_NUMBER));
        map.put(no_records,记录数:+ XMLFunctions.getValue(即no_records));
        map.put(no_entries,报名号+ XMLFunctions.getValue(即no_entries));
        mylist.add(图)
        * /
    }

    ListAdapter适配器=新SimpleAdapter(这一点,mylist中,R.layout.search_result_display_list,
                    新的String [] {cover_image,标题,作者,格式,call_number},
                    新的INT [] {R.id.cover_image,R.id.item_title,R.id.item_author,R.id.item_format,R.id.item_call_number});

    setListAdapter(适配器);

    最终的ListView LV = getListView();
    lv.setTextFilterEnabled(真正的);
    /*lv.setOnItemClickListener(new OnItemClickListener(){
        公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
            @燮pressWarnings(未登记)
            HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)lv.getItemAtPosition(位置);
            Toast.makeText(SearchResult.this,ID+ o.get(ID)+'被点击了。,Toast.LENGTH_LONG).show();

        }
    }); * /
}

 私有静态字符串getTagValue(字符串鹿,元素eElement){
        节点列表nlList = eElement.getElementsByTagName(雄鹿).item(0).getChildNodes();
        节点n值=(节点)nlList.item(0);

        返回nValue.getNodeValue();
     }
}
 

这是我的 XMLFunctions.java 在这里我分析我的XML数据:

 公共类XMLFunctions {

公共最后静态文件XMLfromString(XML字符串){

    文档DOC = NULL;

    DocumentBuilderFactory的DBF = DocumentBuilderFactory.newInstance();
    尝试 {

        DocumentBuilder的DB = dbf.newDocumentBuilder();

        InputSource的是=新的InputSource();
        is.setCharacterStream(新StringReader(XML));
        DOC = db.parse(是);

    }赶上(的ParserConfigurationException E){
        的System.out.println(XML解析错误:+ e.getMessage());
        返回null;
    }赶上(的SAXException E){
        的System.out.println(错的XML文件的结构:+ e.getMessage());
        返回null;
    }赶上(IOException异常E){
        的System.out.println(I / O exeption:+ e.getMessage());
        返回null;
    }

    返回文档;

}

/ **返回元素值
  *参数ELEM元素(这是XML标记)
  返回:元素的值,否则空字符串
  * /
 公共最后静态字符串getElementValue(节点ELEM){
     节点的孩子;
     如果(ELEM!= NULL){
         如果(elem.hasChildNodes()){
             对于(孩子= elem.getFirstChild();!小子= NULL;孩子= kid.getNextSibling()){
                 如果(kid.getNodeType()== Node.TEXT_NODE){
                     返回kid.getNodeValue();
                 }
             }
         }
     }
     返回 ;
 }

 公共静态字符串getSetNoXML(字符串searchItems){
        串线= NULL;

        尝试 {

            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            //要求项目的SET_NUMBER
            HTTPGET requestSetNumber =新HTTPGET(http://spark.opac.tp.edu.sg/X?op=find&scan_$c$c=find_wrd&request=+ searchItems +&放大器;基地= tpl01);

            HTT presponse HTT presponse = httpClient.execute(requestSetNumber);
            HttpEntity httpEntity = HTT presponse.getEntity();
            行= EntityUtils.toString(httpEntity);

        }赶上(UnsupportedEncodingException E){
            行=<找到状态= \错误\><味精>无法连接到服务器16; /味精>< /查找>中;
        }赶上(MalformedURLException异常E){
            行=<找到状态= \错误\><味精>无法连接到服务器16; /味精>< /查找>中;
        }赶上(IOException异常E){
            行=<找到状态= \错误\><味精>无法连接到服务器16; /味精>< /查找>中;
        }
        回线;
}

 公共静态字符串getRecordsXML(字符串setNumber){
        串线= NULL;

        尝试 {

            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            通过SET_NUMBER //请求记录
            HTTPGET requestRecords =新HTTPGET(http://spark.opac.tp.edu.sg/X?op=$p$psent&set_no=+ setNumber +&放大器; set_entry = 000000001,000000002,000000003,+
                    000000004,000000005,000000006,000000007,000000008,000000009,000000010和放大器;格式=马克);


            HTT presponse HTT presponse = httpClient.execute(requestRecords);
            HttpEntity httpEntity = HTT presponse.getEntity();
            行= EntityUtils.toString(httpEntity);

        }赶上(UnsupportedEncodingException E){
            行=<找到状态= \错误\><味精>无法连接到服务器16; /味精>< /查找>中;
        }赶上(MalformedURLException异常E){
            行=<找到状态= \错误\><味精>无法连接到服务器16; /味精>< /查找>中;
        }赶上(IOException异常E){
            行=<找到状态= \错误\><味精>无法连接到服务器16; /味精>< /查找>中;
        }
        回线;
}

公共静态INT numResults(DOC文件){
    节点的结果= doc.getDocumentElement();
    INT RES = -1;

    尝试{
        RES = Integer.valueOf(results.getAttributes()getNamedItem(查找)getNodeValue());
    }赶上(例外五){
        RES = -1;
    }

    返回水库;
}

公共静态字符串的getValue(元素项,字符串str){
    节点列表N = item.getElementsByTagName(STR);
    返回XMLFunctions.getElementValue(n.item(0));
}
}
 

最后,这是从输出的 LogCat中

  

十月4日至25日:20:15.932:ERROR / AndroidRuntime(418):致命异常:主要
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):java.lang.RuntimeException的:无法启动的活动ComponentInfo {joel.TPLibrary / joel.TPLibrary.SearchResult}:显示java.lang.NullPointerException
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.access $ 2300(ActivityThread.java:125)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2033)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.os.Handler.dispatchMessage(Handler.java:99)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.os.Looper.loop(Looper.java:123)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在android.app.ActivityThread.main(ActivityThread.java:4627)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在java.lang.reflect.Method.invokeNative(本机方法)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在java.lang.reflect.Method.invoke(Method.java:521)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)   10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在dalvik.system.NativeStart.main(本机方法)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):由:显示java.lang.NullPointerException    10月四号至25日:20:15.932:ERROR / AndroidRuntime(418):在joel.TPLibrary.SearchResult.getTagValue(SearchResult.java:89)
  10月4号至25号:20:15.932:ERROR / AndroidRuntime(418):在joel.TPLibrary.SearchResult.onCreate(SearchResult.java:58)

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

解决方案

我认为你会有关Android的错误的方式解析XML。坦白的code看起来更凌乱比它需要。

相反,我会使用基于注解的XML框架称为简单这将帮助你编写和输出XML推荐易:我喜欢它,以至于的我甚至写了一篇关于如何将其包含在你的Andr​​oid项目的博客帖子

如果你提供一些示例XML那么我可以给你什么错误的详细信息。

I'm currently trying to parse data from a xml using dynamically. So I'm trying to retrieve data via different tags and insert them into different textviews using SimpleAdapter. But its failing when in my point of view, its supposed to work. Please help me figure this out.

This is my 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();    
     }
}

This is my XMLFunctions.java where I parse my xml data:

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

Lastly, this is the output from LogCat:

04-25 10:20:15.932: ERROR/AndroidRuntime(418): FATAL EXCEPTION: main
04-25 10:20:15.932: ERROR/AndroidRuntime(418): java.lang.RuntimeException: Unable to start activity ComponentInfo{joel.TPLibrary/joel.TPLibrary.SearchResult}: java.lang.NullPointerException
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.os.Handler.dispatchMessage(Handler.java:99)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.os.Looper.loop(Looper.java:123)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at 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): Caused by: 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): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-25 10:20:15.932: ERROR/AndroidRuntime(418): ... 11 more

解决方案

I think that you are going about parsing XML in android the wrong way. Frankly the code looks much more messy than it needs to be.

Instead I would recommended using the annotation based XML framework called Simple which will help you to write and output XML easily: I like it so much that I even wrote a blog post about how to include it in your Android projects.

If you provide some example XML then I can give you more info on what is going wrong.

这篇关于解析XML数据的意外失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆