我正在使用以下代码来解析 XML,它已从官方 Android Docs 中引用:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(response));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag " + xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag " + xpp.getName());
} else if (eventType == XmlPullParser.TEXT) {
// System.out.println("Text " + xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
在控制台上:
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ Start document
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ Start tag exareceipts
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ Start tag email
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ End tag email
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ Start tag authentication_status
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ End tag authentication_status
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ End tag exareceipts
06-08 11:13:25.557 24857-24883/ex.com.receipts I/System.out﹕ End document
但是我只对名为 authentication_status
的节点感兴趣,为此我知道我需要检查:
if(xpp.getName().equalsIgnoreCase("authentication_status")){
//logic for getting node value
}
我真的很困惑和不确定 - 将这段代码放在哪里。
最佳答案
好吧,这是怎么做的:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
String tagName = null;
xpp.setInput(new StringReader(response));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag " + xpp.getName());
tagName = xpp.getName();
} else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag " + xpp.getName());
} else if (eventType == XmlPullParser.TEXT) {
if(tagName.equalsIgnoreCase("authentication_status")){
System.out.println("Text tagName " + xpp.getText());
}
}
eventType = xpp.next();
}
System.out.println("End document");
关于java - 如何在 XML Pull Parser 中获取特定节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702037/