簡體   English   中英

使用XPath解析XML

[英]Parsing XML with XPath

我正在編寫一個簡單的Android應用程序,以使用XPath在ListView中顯示XML內容。 我的代碼在下面給出。 它正在捕獲空異常。 請幫助我:(我嘗試過Google和其他教程,但它們似乎都無法解決我的問題:(

public class MainActivity extends ListActivity {

ArrayList<String> mPeople = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        parseData();
    } catch(Exception ex) {
        Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        System.out.println(ex.getMessage() +"==============");

    }

    // pass adapter w/ data queried through XPath to ListView
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
    setListAdapter(adapter);
}

private void parseData() throws Exception {    
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(new URL("http://www.w3schools.com/xpath/books.xml").openStream());
// query XPath instance, this is the parser
XPath xpath = XPathFactory.newInstance().newXPath();
// specify the xpath expression
// String expression = " /bookstore/book/title ";

XPathExpression e = xpath.compile("/bookstore/book/title");

// list of nodes queried
NodeList nodes = (NodeList)e.evaluate(doc, XPathConstants.NODESET);

Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
// if node found
if(nodes != null && nodes.getLength() > 0) {
  mPeople.clear();
  int len = nodes.getLength();
  for(int i = 0; i < len; ++i) {
      // query value
      Node node = nodes.item(i);
      mPeople.add(node.getTextContent());
  }
}
}
}

我得到的輸出是Toast containsg Exception:null。 我認為openStream()中的db.parse()返回null 如果有人找到解決方案,請告訴我,我們將不勝感激。 謝謝。

編輯:這是Logcat

06-01 10:25:42.586: I/System.out(1401): null==============
06-01 10:25:45.721: I/Choreographer(1401): Skipped 210 frames!  The application may be doing too much work on its main thread.
06-01 10:25:47.226: I/Choreographer(1401): Skipped 1768 frames!  The application may be doing too much work on its main thread.
06-01 10:25:47.467: D/gralloc_goldfish(1401): Emulator without GPU emulation detected.

嘗試使用asynctask執行parseData()功能,並從活動oncreate調用asynctask.execute。它可能會解決您的問題。 這有一個錯誤-應用程序可能在主線程上做過多的工作,僅僅是因為您在主線程上進行網絡調用,因為它可能需要6秒鍾以上的時間,因為應用程序可能會將其視為“ ANR”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM