在 Android 上解析 XML
Parsing XML on Android
有很多解析复杂 XML 的技巧,但我想要一个简单 XML 的解析,例如:
<map>
<string name="string_1">Hello there</string>
<string name="string_2">This is Mium.</string>
</map>
我正在尝试使用 SAXParser(我不确定使用哪个:SAXParser 或 XMLPullParser),所以我正在查看 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)
{
}
}
但是,XML 解析起来已经很复杂了。
我应该如何编码才能解析?
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");
}
其中获取值:
private static String getValue(String tag, Element element)
{
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
有很多解析复杂 XML 的技巧,但我想要一个简单 XML 的解析,例如:
<map>
<string name="string_1">Hello there</string>
<string name="string_2">This is Mium.</string>
</map>
我正在尝试使用 SAXParser(我不确定使用哪个:SAXParser 或 XMLPullParser),所以我正在查看 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)
{
}
}
但是,XML 解析起来已经很复杂了。 我应该如何编码才能解析?
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");
}
其中获取值:
private static String getValue(String tag, Element element)
{
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}