且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用DOM解析Android XML布局文件

更新时间:2023-09-27 17:10:58

如果要使用Java DOM,请尝试执行类似的操作

If you want to use Java DOM, try doing something like this

    final String ANDROID_ID = "android:id";

    try {

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

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

        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) {
        e.printStackTrace();
    }

执行此操作的方法可能更有效(例如,使用SAX),但是它可以工作.

There are probably much more efficient ways to do this (like using SAX instead), but it works.