0

我有一个存储在 URL 上的 XML。我正在从我的 Android 应用程序中解析该 URL。让网址为

http://www.w3schools.com/xpath/books.xml

我想使用 XPath 遍历一些节点并显示结果。但是当我阅读教程时,我开始知道 XML 文件必须存储在项目中。我的意思是这样的:

Document document = builder.parse(new File("/books.xml"));

如果我提供 XML 文件的 URL 即http://www.w3schools.com/xpath/books.xml而不是先保存文件然后使用它,XPath 可以工作吗?

编辑:这是代码:

public class MainActivity extends ListActivity {
// data
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();
    }

    // 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 {
    // create an InputSource object from /res/raw

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new URL("http://www.w3schools.com/xpath/books.xml").openConnection().getInputStream());
       doc.getDocumentElement().normalize();
    // query XPath instance, this is the parser
    XPath xpath = XPathFactory.newInstance().newXPath();
    // specify the xpath expression
    String expression = " /bookstore/book/title ";
    // list of nodes queried
    NodeList nodes = (NodeList)xpath.evaluate(expression, 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());
        }
    }
}

任何帮助将不胜感激。

4

0 回答 0