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

Che*_*ung 3 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>
Run Code Online (Sandbox Code Playgroud)

代码:

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());
        }
Run Code Online (Sandbox Code Playgroud)

那么,getNodeValue()有什么问题?

在此输入图像描述

还有一个问题,我如何将Eclipse设置为Visual Studio,如果有任何错误,它将在源代码行文件中断行,而不是仅在调试窗口上打印出堆栈消息.

更新1. 我发现这篇文章:org.w3c.dom.Node,Android版本小于2.2 org.w3c.dom.Node,Android版本低于2.2

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

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

Che*_*ung 12

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

我用 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());
            }
        }
Run Code Online (Sandbox Code Playgroud)

第3行很重要,我记录了hasChildNodes()并在LogCat中观察,不知道为什么它包含一个名为"#text"的节点而没有子节点(在logcat上为false).

但我相信我的XML格式正确.谷歌之后,发现了很多解释. https://www.google.com/search?q=xml+%23text

在此输入图像描述


Chr*_*ken 9

使用getTextContent()方法.

node.getTextContent()
Run Code Online (Sandbox Code Playgroud)

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