我需要使用的API不支持xpath,有点头疼! :-( 哈哈
我要解析的 xml 是一个字符串。我的问题:
- 是否有“simplexml_load_string”的 Java 等效项,它将字符串转换为 xml 文档以供解析?
- 哪个更适合解析,SAX 还是 DOM?我需要从 XML 中获取几个值,而且结构不是那么深。 [3 个级别]
谢谢!
最佳答案
也许这对你有帮助
//http://developer.android.com/intl/de/reference/android/content/res/XmlResourceParser.html
import org.xmlpull.v1.XmlPullParserException;
try {
XmlResourceParser xrp = ctx.getResources().getXml(R.xml.rules);
while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xrp.getEventType() == XmlResourceParser.START_TAG) {
String s = xrp.getName();
if (s.equals("category")) {
String catname = xrp.getAttributeValue(null, "name");
String rule = xrp.getAttributeValue(null, "rule");
}
} else if (xrp.getEventType() == XmlResourceParser.END_TAG) {
;
} else if (xrp.getEventType() == XmlResourceParser.TEXT) {
;
}
xrp.next();
}
xrp.close();
} catch (XmlPullParserException xppe) {
Log.e(TAG(), "Failure of .getEventType or .next, probably bad file format");
xppe.toString();
} catch (IOException ioe) {
Log.e(TAG(), "Unable to read resource file");
ioe.printStackTrace();
}
关于java - Android 中的 XML 解析 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3222484/