问题
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