繁体   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