Simple XML Parsing in Android
My xml is shown below:
<.sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==<./sUID>
<.Shipping>0.00<./Shipping>
<.DocType开发者_StackOverflow社区>SO<./DocType>
How do I parse this simple xml in Android?
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");
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)
精彩评论