1

我想解析一个 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:只允许一个根元素

4

1 回答 1

1

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

qrCode = "<html>" + qrCode + "</html>";
于 2019-05-30T09:49:15.937 回答