我的 XML 如下所示:
<.sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==<./sUID>
<.Shipping>0.00<./Shipping>
<.DocType>SO<./DocType>
我该如何在Android中解析这个简单的xml?
我的 XML 如下所示:
<.sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==<./sUID>
<.Shipping>0.00<./Shipping>
<.DocType>SO<./DocType>
我该如何在Android中解析这个简单的xml?
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;
}
Document doc = x.XMLfromString("<XML><sUID>yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==</sUID> <Shipping>0.00</Shipping> <DocType>SO</DocType></XML>");
NodeList nodes = doc.getElementsByTagName("XML");
使用默认的拉取式XML解析器很繁琐和容易出错,因为API过于底层。建议使用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)
将打印 Shipment(uid=yPkmfG3caT6cxexj5oWy34WiUUjj8WliWit45IzFVSOt6gymAOUA==, shipping=0.00, docType=SO)