微信开发中用dom4j解析消息时的错误

我用dom4j解析微信xml消息时用这种方法Document document = reader.read(inputStream);
他报错Error on line 1 of document : The root element is required in a well-formed document. Nested exception: The root element is required in a well-formed document.通过分析我感就是(如果我错了请兄弟们指出)用SAXReader他会严格检查xml头部但是微信回复消息如下

<xml>
 <ToUserName>ToUserName>
 <FromUserName>FromUserName> 
 <CreateTime>1348831860CreateTime>
 <MsgType>MsgType>
 <Content>Content>
 <MsgId>1234567890123456MsgId>
 xml>

一点都不标准,但是可以采用下面的方法

    // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 一定要utf-8
        InputStreamReader inputReader = new InputStreamReader(inputStream,
                "UTF-8");
        BufferedReader buffer = new BufferedReader(inputReader);
        String message = "";
        String s = "";
        while ((s = buffer.readLine()) != null) {
            message += s;
        }
        System.out.println(message);
        System.out.println("获取输入流");
        // // 读取输入流
         SAXReader reader = new SAXReader();
//       Document document = reader.read(inputStream);
        // 将字符串转化为XML文档对象
        Document document = DocumentHelper.parseText(message);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        // 遍历根节点下所有子节点
        Iterator iter = root.elementIterator();

        // // 遍历所有子节点
        // for (Element e : elementList) {
        // System.out.println(e.getName() + "|" + e.getText());
        // map.put(e.getName(), e.getText());
        // }
        while (iter.hasNext()) {
            Element ele = (Element) iter.next();
            map.put(ele.getName(), ele.getText());

        }
        // 释放资源
        inputStream.close();

你可能感兴趣的:(java微信开发,微信)