【发布时间】:2011-09-15 23:57:22
【问题描述】:
我已经尝试让它工作了大约三个小时。这是我尝试的两段代码和 xml 文件的链接。有人可以告诉我我做错了什么或如何轻松做到这一点?我只想将当前温度存储为“current_conditions”元素中的“temp_f”。如果有比我的任何尝试更好的方法,我很想知道。非常感谢!
这是我从网上下载的 xml 文件的链接: http://www.google.com/ig/api?weather=10598
这是我用来从网络获取 xml 数据的代码:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
// HttpGet get = new HttpGet();
try {
HttpResponse rsp = client.execute(get);
String xmltemp = EntityUtils.toString(rsp.getEntity());
System.out.println(xmltemp);
然后我尝试了这两种方法来尝试解析 xml,但都没有成功。
DocumentBuilderFactory factory1 = DocumentBuilderFactory
.newInstance();
factory1.setNamespaceAware(true); // never forget this!
InputSource source = new InputSource(new StringReader(xmltemp));
Document doc = factory1.newDocumentBuilder().parse(source);
doc.getDocumentElement().normalize();
System.out.println("Root element "
+ doc.getDocumentElement().getNodeName());
Log.d("OUTPUT","Root element "
+ doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("weather");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = ((Document) fstElmnt)
.getElementsByTagName("module_id");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = ((Node) fstNmElmnt).getChildNodes();
System.out.println(((Node) fstNm.item(0)).getNodeValue());
newal.add("" + ((Node) fstNm.item(0)).getNodeValue());
Log.d("OUTPUT","" + ((Node) fstNm.item(0)).getNodeValue());
}
}
还有这个:
DocumentBuilderFactory factory1 = DocumentBuilderFactory
.newInstance(); factory1.setNamespaceAware(true); // never forget this!
InputSource source = new InputSource(new
StringReader(xmltemp)); Document doc =
factory1.newDocumentBuilder().parse(source);
XPathFactory factory11 = XPathFactory.newInstance(); XPath xpath1
= factory11.newXPath(); XPathExpression expr1 = xpath1 .compile(
"//forecast_information[postal_code='10598']/forecast_date/text()"
); Object result = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result; for (int i = 0; i <
nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
Log.d("1010101010101",nodes.item(i).getNodeValue()); }
编辑: 所以这是我现在尝试使用的代码,但每次我运行它时,我都会在 logcat 中得到这个错误:
09-15 20:26:47.359: DEBUG/ErOr(17663): java.lang.ClassCastException: org.apache.harmony.xml.dom.ElementImpl
这是代码:
DocumentBuilderFactory factory1 = DocumentBuilderFactory.newInstance();
factory1.setNamespaceAware(true); // never forget this!
InputSource source = new InputSource(new StringReader(xmltemp));
Document doc = factory1.newDocumentBuilder().parse(source);
String newstring = "" + ((DocumentBuilderFactory) ((Document) doc.getDocumentElement().
getElementsByTagName("current_conditions").item(0)).
getElementsByTagName("temp_f").item(0)).
getAttribute("data");
【问题讨论】: