一、maven依耐:
<!-- https://mvnrepository.com/artifact/xpp3/xpp3 -->
<dependency>
<groupId>xpp3</groupId>
<artifactId>xpp3</artifactId>
<version>1.1.4c</version>
</dependency>
二、工具类:
public class XPPParserUtils {
private static XmlPullParserFactory parserFactory = null;
static {
try {
parserFactory = XmlPullParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
} catch (XmlPullParserException e) {
System.out.println("XPPParser initialize error!!");
}
}
public static Map<String,String> parse(String strXML) {
return parse(new StringReader(strXML));
}
/**
* 深度解析XML格式流,获取所有子元素名和值
* @param reader
* @return Map<String,String>
*/
public static Map<String,String> parse(Reader reader) {
Map<String,String> map = new HashMap<String,String>();
try {
XmlPullParser xpp = parserFactory.newPullParser();
xpp.setInput(reader);
int eventType = xpp.getEventType();
String currentTag = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} else if(eventType == XmlPullParser.TEXT) {
map.put(currentTag, xpp.getText());
}
eventType = xpp.next();
}
} catch (Exception ex) {
System.out.println("xml parse exception:" + ex);
}
return map;
}
}
三、测试代码:
/**
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<employees>
<head>
<version>v1.0.7.6</version>
<charset>UTF-8</charset>
</head>
<body>
<employee>
<name>ddviplinux</name>
<sex>m</sex>
<age>30</age>
</employee>
</body>
</employees>
*/
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><employees><head><version>v1.0.7.6</version><charset>UTF-8</charset></head><body><employee><name>ddviplinux</name><sex>m</sex><age>30</age></employee></body></employees>";
Map<String, String> parseMap = XPPParserUtils.parse(xmlString);
System.out.println(parseMap);//{charset=UTF-8, sex=m, name=ddviplinux, version=v1.0.7.6, age=30}