我正在解析 XML 文件,如下所示:
<ROW>
<INDUSTRY_ID>1</INDUSTRY_ID>
<ID>314</ID>
</ROW>
这是我的代码:
NodeList titleList = list.getElementsByTagName("ROW");
Log.w("nodeName is ",titleList.item(0).getChildNodes().item(1).getFirstChild().getNodeName());
Log.w("nodeValue is ",titleList.item(0).getChildNodes().item(1).getFirstChild().getNodeName());
我可以成功获取标签和标签的内容,即分别得到“1”和“314”;但是,我从 getNodeName() 获得了#text。 我也尝试过:
titleList.item(0).getChildNodes().item(1).getFirstChild().getNodeName().toString()
但我仍然收到#text。我的问题是如何获取“INDUSTRY_ID”和“ID”?
最佳答案
您已导航到文本节点。从技术上讲,文本节点没有名称,只有(文本)值。你想要这个:
NodeList titleList = list.getElementsByTagName("ROW");
Log.w("nodeName is ",titleList.item(0).getChildNodes().item(1).getNodeName());
Log.w("nodeValue is ",titleList.item(0).getChildNodes().item(3).getNodeName());
但是,这是一种非常不可靠的访问元素节点和值的方法,因为它依赖于空白格式。使用 Xpath 检索所需元素的列表并访问它们各自的名称和值
XPath xp = XPathFactory.newInstance();
NodeList elements = (NodeList) xp.evaluate(doc, "//ROW/*", XPathConstants.NODESET);
for(int i=0; i < elements.getLength(); ++i) {
String name = elements.itemt(i).getNodeName();
String value = elements.itemt(i).getTextContent();
}
关于java - 将 #text 从 getNodeName 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7221637/