如何在Java中获取节点中的元素文本?
我是
Android Development的新手,想要解析XML并绑定到Google MapView.
但是,我无法读取元素之间的文本. XML <?xml version="1.0" encoding="utf8"?> <table name="clinicaddress"> <row> <GeoPoint>22.3852860,113.9664120</GeoPoint> </row> <row> <GeoPoint>22.336950,114.1578720</GeoPoint> </row> </table> 代码: import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; try { inputStream = assetManager.open("clinics.xml"); String xmlRecords = readTextFile(inputStream); //Log.e("Clinics XML",xmlRecords); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlRecords)); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(is); doc.getDocumentElement ().normalize (); NodeList listOfClinics = doc.getElementsByTagName("row"); Log.e("listOfClinics Length",String.valueOf(listOfClinics.getLength())); //Loop the XML for (int x = 0; x < listOfClinics.getLength(); x++) { Node ClinicNode = listOfClinics.item(x); NodeList ClinicInfo = ClinicNode.getChildNodes(); for (int y = 0; y < ClinicInfo.getLength(); y++) { Node info = ClinicInfo.item(y); Log.e(info.getNodeName(),info.getNodeValue()); //<--Error on info.getNodeValue() } } //End Loop XML } catch (Exception e) { Log.e("tag",e.getMessage()); } 那么,getNodeValue()有什么问题? 还有一个问题,我如何将Eclipse设置为Visual Studio, 更新1.
但是,我试试这个,也是错误的. 解决方法
最后,我得到了这个作品.
我使用info.getFirstChild().getNodeValue() for (int y = 0; y < ClinicInfo.getLength(); y++) { Node info = ClinicInfo.item(y); if (info.hasChildNodes()) { Log.e(info.getNodeName(),info.getFirstChild().getNodeValue()); } } 第3行很重要,我记录了hasChildNodes()并在LogCat中观察,不知道为什么它包含一个名为“#text”的节点而没有子节点(在logcat上为false). 但我相信我的XML格式正确. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |