Android解析XML格式字符串

  • Pull解析方式
    比如解析以下一段xml字符串:

    
        Google Maps
        1.0
    
    
        Chrome
        2.1
    

示例代码:

public void parseXMLWithPull(String xmlData) throws Exception{
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser parser = factory.newPullParser();
    parser.setInput(new StringReader(xmlData));
    int eventType = parser.getEventType();
    String name = "";
    String version = "";
    while (eventType != XmlPullParser.END_DOCUMENT) {
        String nodeName = parser.getName();
        switch (eventType) {
            // 开始解析某个结点
            case XmlPullParser.START_TAG: {
                if ("name".equals(nodeName)) {
                    name = parser.nextText();
                } else if ("version".equals(nodeName)) {
                    version = parser.nextText();
                }
                break;
            }
            // 完成解析某个结点
            case XmlPullParser.END_TAG: {
                if ("app".equals(nodeName)) {
                    Log.d("MainActivity", "name is " + name);
                    Log.d("MainActivity", "version is " + version);
                }
                break;
            }
            default:
                break;
        }
        eventType = parser.next();
    }
}

你可能感兴趣的:(Android解析XML格式字符串)