我无法在Android中使用saxParser打开XML文件

时间:2014-06-03 19:09:35

标签: java android xml

我正在学习解析XML,在我使用它的教程中是saxParser。不幸的是有些东西无效。我不知道问题出在哪里。

代码MainActivity.java:

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_parse) {
        doParsing();
        Toast.makeText(getBaseContext(), "lool", Toast.LENGTH_LONG).show();
        Log.w("XML parsin", "you choose option");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void doParsing(){

    URL urlRequest = null;

    try {
        urlRequest = new URL("file:///mnt/sdcard/osm.xml");
    } catch (MalformedURLException e) {
    }

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp;
    XMLReader xr=null;

    try {
        sp = spf.newSAXParser();
        xr = sp.getXMLReader();
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    }

        myExampleHandler = new ExampleHandler(); 
        xr.setContentHandler(myExampleHandler); 

        try { xr.parse(new InputSource(urlRequest.openStream())); } 
        catch (IOException e) { } 
        catch (SAXException e) { } 
}

Code ExampleHandler.java:

package com.example.parsowanie;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;
import android.widget.Toast;

public class ExampleHandler extends DefaultHandler {

public ExampleHandler() {
    // TODO Auto-generated constructor stub
}

@Override
public void startDocument() throws SAXException {
    Log.w("XML parsin", "starting parsing document");
}

@Override
public void endDocument() throws SAXException {
    // TODO Auto-generated method stub
    super.endDocument();
}

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    // TODO Auto-generated method stub
    super.endElement(uri, localName, qName);
}

所以我在手机上的SD卡上有文件.xml。在LogCat中我得到了

    06-03 14:57:15.603: W/XML parsin(6578): you choose option

用于选择菜单中的按钮 但我无法到达

    Log.w("XML parsin", "starting parsing document");

消息,这意味着应用程序无法打开我的.xml文件。

任何人都知道问题在哪里?

1 个答案:

答案 0 :(得分:0)

需要检查两件事:

  1. 尝试file:///sdcard/osm.xml代替file:///mnt/sdcard/osm.xml
  2. 您是否错过READ_EXTERNAL_STORAGE档案中的AndroidManifest.xml权限?

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />