【问题标题】:Parsing XML with XPath使用 XPath 解析 XML
【发布时间】:2013-06-01 10:27:35
【问题描述】:

我正在编写一个简单的 Android 应用程序来使用 XPath 在 ListView 中显示 XML 内容。我的代码在下面给出。它正在捕获空异常。请帮助我:(我试过谷歌和不同的教程,但似乎没有一个能解决我的问题:(

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:null。我认为db.parse() 中的openStream() 正在返回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.

【问题讨论】:

    标签: java android xml xpath domparser


    【解决方案1】:

    尝试使用 asynctask 执行 parseData() 功能 并从活动 oncreate.it 调用 asynctask.execute 可能会解决您的问题。 你得到了错误 - 应用程序可能在其主线程上做太多工作只是因为你在主线程上进行网络调用,因为它可能需要超过 6 秒的时间,因为应用程序可能会将其视为“ANR " 按操作系统。

    【讨论】:

    • 实际上是这条线返回nullDocument doc = db.parse(new URL("http://www.w3schools.com/xpath/books.xml").openStream());
    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2012-04-07
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多