Android XML解析错误:仅允许一个根元素

时间:2019-05-30 09:46:39

标签: java android xml dom xml-parsing

我想解析XML。我在下面发布我的XML响应。在里面 pre 标记我得到一个要打印的JSON,但无法解析我的代码。我正在发布代码以解析此XML。

private void xmlParsing(String qrCode) {
        try {
            qrCode = qrCode.replaceAll("[^\\x20-\\x7e]", "");
            //loge("qrCode : " + qrCode);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(qrCode.getBytes("utf-8")));

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("head");
            loge("--df--nList.getLength()---"+nList.getLength());
            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


<head></head>
<body>
    <pre style="word-wrap: break-word; white-space: pre-wrap;">{"status":true,"message":"Login Successfull","data":{"user":{"id":2,"name":"Rommy Garg","email":"rommy@signitysolutions.com","user_group_id":"2","company_id":2,"last_login":"2019-05-29 05:48:27","last_logout":"2019-05-28 10:33:39","profile_pic":null,"created_at":"2018-12-20 10:12:23","updated_at":"2019-05-29 05:48:27","sf_reference_id":"0056F00000BqMZSQA3","sf_setup":1},"company_logo":"http:\/\/staging.sales-chap.com\/dist\/uploads\/company\/1545300743.jpg","client_id":1,"client_secret":"IQ09J2BdDuc3lSKUJlQAp8uhCXRq+s2EucsBOb9rfjo="}}</pre>
</body>

但是我遇到了以下错误:

  

org.w3c.dom.DOMException:仅允许一个根元素

1 个答案:

答案 0 :(得分:1)

好吧,正如错误所说,XML只允许一个根元素。您可以在收到的字符串周围创建一个假的:

qrCode = "<html>" + qrCode + "</html>";