【发布时间】:2011-03-30 08:29:41
【问题描述】:
我需要 Android 中 Xml-Parsing 的详细教程或示例
【问题讨论】:
标签: android xml xml-parsing
我需要 Android 中 Xml-Parsing 的详细教程或示例
【问题讨论】:
标签: android xml xml-parsing
你可以看看这篇文章...
他们会很好地讨论 Android 中可用的所有 3 种解析器以及代码示例
http://www.ibm.com/developerworks/opensource/library/x-android/index.html
【讨论】:
您在 Android 上解析 XML 就像在常规 Java 中一样。您在 Android 中同时拥有 org.w3c.dom 和 org.xml.sax 软件包。使用最适合您需要的一种,Internet 上提供了很多关于这两种方法的教程。
【讨论】:
通过 HTTP 请求获取 XML 内容
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
解析 XML 内容并获取 DOM 元素
public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
通过传递元素节点名称获取每个xml子元素值
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
【讨论】: