xpp3
官网
http://www.extreme.indiana.edu/xgws/xsoap/xpp/
简介
Xml Pull Parser (in short XPP) is a streaming pull XML parser and should be used when there is a need to process quickly and efficiently all input elements (for example in SOAP processors).
sax
官网
http://www.saxproject.org/
简介
SAX is the Simple API for XML, originally a Java-only API. SAX was the first widely adopted API for XML in Java, and is a “de facto” standard. The current version is SAX 2.0.1, and there are versions for several programming language environments other than Java.
示例:解析微信post消息
当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上。
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[this is a test]]></Content> <MsgId>1234567890123456</MsgId> </xml
以下是java代码片段:
import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 消息工具类 * */ public class WeixinUtils { /** * 解析微信发来的请求(XML) * * @param request * @return * @throws IOException */ @SuppressWarnings("unchecked") public static Map<String, String> parseXml(HttpServletRequest request) throws IOException { ServletInputStream inputStream = request.getInputStream(); SAXReader reader = new SAXReader(); Map<String, String> resultMap = null; try { // 这个 doc 不会是 null Document document = reader.read(inputStream); Element rootElement = document.getRootElement(); List<Element> eList = rootElement.elements(); resultMap = new HashMap<String, String>(); for (Element e : eList) { resultMap.put(e.getName(), e.getText()); } } catch (DocumentException e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); } return resultMap; } }
ps:
想知道 void java.io.InputStream.close() throws IOException 怎么用吗?
Ctrl+Shift+G 看看别人怎么用的吧