How to use DOM to read XML within Android applications correctly?

感情迁移 提交于 2019-12-13 08:19:55

问题


I'm able to get the information I want if the XML file is stored locally on my machine, but reading it when stored on the phone isn't working very well.

I've tried XMLPullParser but it extracts binary information about the id names etc and I'd like the actual name.

Code:

    final String ANDROID_ID = "android:id";

            try {
                File fXmlFile = new File("res/layout/page1.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);
                doc.getDocumentElement().normalize();

                NodeList nList = doc.getElementsByTagName("Button");

                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node nNode = nList.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;

                        if (eElement.hasAttribute(ANDROID_ID))
                            System.out.println("ID: "
                                    + eElement.getAttribute(ANDROID_ID));
                    }
                }
            } 

            catch (Exception e) {
                System.out.println("Catch");


  e.printStackTrace();
        }

回答1:


in the XmlPullParser documentation there is a getAttributeCount() and getAttributeByName(int index) that might be useful. You must use it in START_TAG




回答2:


Over XML parsing this link describes well. Here you can find other parsers too with xmlPullParser.



来源:https://stackoverflow.com/questions/8202864/how-to-use-dom-to-read-xml-within-android-applications-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!