2

如何解析位于资产文件夹中的本地 XML 文件?在此示例中,我从 URL 获取 XML,如何获取 XML?

public class AndroidXMLParsingActivity extends ListActivity {

    // All static variables
    static final String URL = "http://api.androidhive.info/pizza/?format=xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
            map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
4

1 回答 1

4

从 assets 文件夹中访问文件真的很容易,例如,如果您想从 assets 目录中读取“test.xml”,您可以使用以下代码。

File file = new File(Environment.getExternalStorageDirectory() + "/new.xml");
        FileInputStream fis = new FileInputStream(file);
        parser.setInput(new InputStreamReader(fis));

        InputStream tinstr = null;
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            AssetManager assetManager = getAssets();
            tinstr = assetManager.open("test.xml");
            parser.setInput(new InputStreamReader(tinstr));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
于 2012-11-07T21:59:34.053 回答