package example.com.networktest.utility;
import android.util.Log;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import javax.xml.parsers.SAXParserFactory;
import example.com.networktest.ContentHandler;
public class ParseXML {
private static final String TAG = "我是ParseXML";
/**
* Pull方式解析xml文件
* @param xmlData 待解析的xml数据
*/
public static void parseXMLWithPull(String xmlData) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
// 还有xmlPullParser.setInput(InputStream,encoding)方法
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
switch (eventType) {
case XmlPullParser.START_TAG: {
if ("id".equals(nodeName)) {
//nextText()方法用于获取当前节点的内容
id = xmlPullParser.nextText();
} else if ("name".equals(nodeName)) {
name = xmlPullParser.nextText();
} else if ("version".equals(nodeName)) {
version = xmlPullParser.nextText();
}
break;
}
//当完成解析"app"节点时,打印出app的节点信息
case XmlPullParser.END_TAG: {
if ("app".equals(nodeName)) {
Log.d(TAG, "id is " + id);
Log.d(TAG, "name is " + name);
Log.d(TAG, "version is " + version);
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
} catch (Exception e) {
Log.d("出现异常", e.toString());
}
}
/**
* SAX方式解析xml文件
* @param xmlData 带解析的xml数据
*/
public static void parseXMLWithSAX(String xmlData) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
//将contentHandler的实例设置到xmlReader中
xmlReader.setContentHandler(new ContentHandler());
//开始解析xml文件
xmlReader.parse(new InputSource(new StringReader(xmlData)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
网友评论