Achin
Achin

Reputation: 1252

Android XML Parsing error: Only one root element allowed

I want to parse an XML. I am posting my XML response below. In the pre tag I am getting a JSON which i want to print but I am not able to parse with my code. I am posting my code to parse this 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":"[email protected]","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>

but I am getting below error:

org.w3c.dom.DOMException: Only one root element allowed

Upvotes: 1

Views: 469

Answers (1)

Mureinik
Mureinik

Reputation: 311428

Well, as the error said, XML only allows a single root element. You could create a fake one around the string you recieve:

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

Upvotes: 1

Related Questions