【发布时间】:2012-02-26 15:17:17
【问题描述】:
我的代码没有检索到包含特殊字符的全部元素节点。 例如,对于这个节点:
<theaterName>P&G Greenbelt</theaterName>
由于与号,它只会检索“P”。我需要检索整个字符串。
这是我的代码:
public List<String> findTheaters() {
//Clear theaters application global
FilmhopperActivity.tData.clearTheaters();
ArrayList<String> theaters = new ArrayList<String>();
NodeList theaterNodes = doc.getElementsByTagName("theaterName");
for (int i = 0; i < theaterNodes.getLength(); i++) {
Node node = theaterNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
//Found theater, add to return array
Element element = (Element) node;
NodeList children = element.getChildNodes();
String name = children.item(0).getNodeValue();
theaters.add(name);
//Logging
android.util.Log.i("MoviefoneFetcher", "Theater found: " + name);
//Add theater to application global
Theater t = new Theater(name);
FilmhopperActivity.tData.addTheater(t);
}
}
return theaters;
}
我尝试添加代码来扩展名称字符串以连接其他 children.items,但它不起作用。我只会得到“P&”。
...
String name = children.item(0).getNodeValue();
for (int j = 1; j < children.getLength() - 1; j++) {
name += children.item(j).getNodeValue();
}
感谢您的宝贵时间。
更新: 找到了一个可以在节点上调用的名为 normalize() 的函数,它结合了所有文本子节点,因此 children.item(0) 包含所有子节点的文本,包括 & 符号!
【问题讨论】:
-
在 XML 内容中不允许使用 &,因此您尝试解析的 XML 无效。
标签: java xml parsing special-characters