我刚刚开始使用DOM并想要解析Android XML布局文件 e.g。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="30dip">
<LinearLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center" >
<EditText android:id="@+id/entry1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
<EditText android:id="@+id/entry2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
<EditText android:id="@+id/entry3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"/>
</LinearLayout>
</LinearLayout>
得到这样的输出(仅在EditText的ID上):
ID: @+id/entry1
ID: @+id/entry2
ID: @+id/entry3
有办法做到这一点吗?有人可以指点我一个教程或给我一些想法吗?
当前代码:
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();
}
谢谢!
答案 0 :(得分:0)
如果您想使用Java DOM,请尝试执行类似这样的操作
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),但它可以工作。