如何在Java中获取节点中的元素文本?

我是Android Development的新手,想要解析XML并绑定到Google MapView。 但是,我无法读取元素之间的文本。

XML

   22.3852860,113.9664120   22.336950,114.1578720  

代码:

 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.我发现这篇文章:org.w3c.dom.Node,Android版本小于2.2 org.w3c.dom.Node,Android版本低于2.2

node.getTextContext()与node.getFirstChild()。getNodeValue()相同。

但是,我试试这个,也是错误的。

最后,我得到了这个作品。

我使用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格式正确。 谷歌之后,发现了很多解释。 https://www.google.com/search?q=xml+%23text

在此处输入图像描述

使用getTextContent()方法。

 node.getTextContent() 

getTextContent()方法返回所有嵌套标记的文本。

文本只是节点的子节点。 你需要遍历GeoPoint节点的所有子节点,检查节点类型是Node.TEXT_NODE并连接文本