问题
There are lots of tips to parse complicated XML but I want a parse for simple XML like:
<map>
<string name="string_1">Hello there</string>
<string name="string_2">This is Mium.</string>
</map>
I was trying to use SAXParser (I'm not sure which to use: SAXParser or XMLPullParser), so I'm looking at Parse XML on Android
public void ParseData(String xmlData)
{
try
{
// Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
// Input Stream
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlData));
// Parse Document into a NodeList
Document doc = db.parse(inStream);
NodeList nodes = doc.getElementsByTagName("ticket");
// Loop NodeList and Retrieve Element Data
for(int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
if (node instanceof Element)
{
Element child = (Element)node;
String id = child.getAttribute("id");
}
}
}
catch(SAXException e)
{
}
}
However, it's already complicated XML parse. How should I code only to parse ?
回答1:
Your loop should look like this:
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
tv1.setText(tv1.getText()+"\nName : " + getValue("name", element)+"\n");
}
where getValue :
private static String getValue(String tag, Element element)
{
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
来源:https://stackoverflow.com/questions/51908821/parsing-xml-on-android