how to parse inner tag of xml in android
This is my xml. please tell me DOM parse method to parse the whole video tag. actually it has an inner tag of location that is disturbing me.
<video>
<video_id>39</video_id>
<title>test video</title>
<description>asdasd asd as</description>
<address/>
<location>
<longitude>-86.785012400000030</longitude>
<latitude>33.353920000000000</latitude>
</location>
<phone>2055开发者_运维知识库555555</phone>
<website>http://www.google.com</website>
<time>154</time>
<youtube_url>http://www.youtube.com/watch?v=sdfgd</youtube_url>
<youtube_video_id>sdfgd</youtube_video_id>
<category_name>User Content</category_name>
<category_id>48</category_id>
</video>
This tutorial might help you http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
Here's an example reading your xml into a Document
object and then using xpath
to evalute the text content of the longitude node. Ensure that the video.xml
is in the classpath of app (put it in same directory as the java).
I only add the xpath as a point of interest to show you how to query the Document
returned.
public class ReadXML {
private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
private static final XPathFactory XPATH_FACTORY = XPathFactory.newInstance();
public static void main(String[] args) throws Exception {
new ReadXML().parseXml();
}
private void parseXml() throws Exception {
DocumentBuilder db = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
InputStream stream = this.getClass().getResourceAsStream("video.xml");
final Document document = db.parse(stream);
XPath xPathEvaluator = XPATH_FACTORY.newXPath();
XPathExpression expr = xPathEvaluator.compile("video/location/longitude");
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node item = nodes.item(i);
System.out.println(item.getTextContent());
}
}
}
精彩评论