Aakash Yatish
Aakash Yatish

Reputation: 31

Simple XML Parsing in Android

My xml is shown below:

<.sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==<./sUID>
<.Shipping>0.00<./Shipping>
<.DocType>SO<./DocType>

How do I parse this simple xml in Android?

Upvotes: 3

Views: 5880

Answers (2)

Martin Vysny
Martin Vysny

Reputation: 3201

Using the default pull XML parser is tedious and error-prone since the API is too low level. Use Konsume-XML:

data class Shipment(val uid: String, val shipping: BigDecimal, val docType: String) {
    companion object {
        fun xml(k: Konsumer): Shipment {
            k.checkCurrent("Shipment")
            return Shipment(k.childText("sUID"),
                    k.childText("Shipping") { it.toBigDecimal() },
                    k.childText("DocType"))
        }
    }
}

val shipment = """
<Shipment>
    <sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==</sUID>
    <Shipping>0.00</Shipping>
    <DocType>SO</DocType>
</Shipment>
""".trimIndent().konsumeXml().child("Shipment") { Shipment.xml(this) }
println(shipment)

will print Shipment(uid=yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==, shipping=0.00, docType=SO)

Upvotes: 1

Mark Mooibroek
Mark Mooibroek

Reputation: 7696

Make a document:

public Document XMLfromString(String v){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(v));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return doc;

    }

Then read it like so:

Document doc = x.XMLfromString("<XML><sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==</sUID> <Shipping>0.00</Shipping> <DocType>SO</DocType></XML>");

NodeList nodes = doc.getElementsByTagName("XML");

Upvotes: 5

Related Questions