XmlPullParser解析xml文件

xml:


    
    
        
            14
            成功
        
    

public String createXml() {    
    StringBuilder sb = new StringBuilder("");     
    sb.append("" + "" +            
        "" + "14" + "成功" +            
        "" + "" + ""    );    
    return sb.toString();
}

解析函数 getCommXml(String xml)

public static String getCommXml(String xml) {    
    String commXml = null;    
    if (xml == null) {        
        return null;    
    }    
    Log.i("dido", xml);    
    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());   
    try {        
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();        
        XmlPullParser parser = factory.newPullParser();        
        parser.setInput(inputStream,"UTF-8"); // 设置数据源编码        
        int eventType = parser.getEventType(); //获取事件类型       
        while (eventType != XmlPullParser.END_DOCUMENT) {     
            switch (eventType) {                
                case XmlPullParser.START_TAG: // 开始读取某个标签                    
                    Log.i("Start tag ", parser.getName());                    
                    break;                
                case XmlPullParser.TEXT:                    
                    commXml = parser.getText();                    
                    Log.i("Text ", parser.getText());                    
                    break;                
                case XmlPullParser.END_TAG:                    
                    Log.i("End tag ", parser.getName());                    
                    break;            
            }            
            eventType = parser.next();        
        }        
        inputStream.close();    
    } catch (Exception e) {        
        e.printStackTrace();    
    }    
    return commXml;
}

输出:

I/dido丫: 14成功
I/Start tag: soapenv:Envelope
I/Start tag: soapenv:Header
I/End tag: soapenv:Header
I/Start tag: soapenv:Body
I/Start tag: AddRecordRes
I/Start tag: code
I/Text: 14
I/End tag: code
I/Start tag: message
I/Text: 成功
I/End tag: message
I/End tag: AddRecordRes
I/End tag: soapenv:Body
I/End tag: soapenv:Envelope

你可能感兴趣的:(XmlPullParser解析xml文件)