Dan*_*Dan 1 java xml parsing special-characters
我的代码不会检索包含特殊字符的整个元素节点.例如,对于此节点:
<theaterName>P&G Greenbelt</theaterName>
Run Code Online (Sandbox Code Playgroud)
由于&符号,它只会检索"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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试添加代码来扩展名称字符串以连接其他children.items,但它不起作用.我只得到"P&".
...
String name = children.item(0).getNodeValue();
for (int j = 1; j < children.getLength() - 1; j++) {
name += children.item(j).getNodeValue();
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间.
更新:找到一个名为normalize()的函数,你可以在Nodes上调用它,它结合了所有文本子节点,所以做一个children.item(0)包含所有孩子的文本,包括&符号!
这&是XML中的转义字符.看起来像这样的XML:
<theaterName>P&G Greenbelt</theaterName>
Run Code Online (Sandbox Code Playgroud)
应该被解析器拒绝.相反,它应该是这样的:
<theaterName>P&G Greenbelt</theaterName>
Run Code Online (Sandbox Code Playgroud)
存在一些这样的字符,例如<(<),>(>),"(")和'(').还有其他方法来转义字符,例如通过它们的Unicode值,如• 或〹.
有关更多信息,XML规范非常清楚.
现在,根据树的构造方式,它可能是另一件事,就是角色被正确转义,你展示的样本不是实际存在的样本,而是数据在树中的表示方式.
例如,当使用SAX构建树时,实体(the- &thingies)会分开并单独传递.这是因为SAX解析器试图返回数据的连续块,并且当它到达转义字符,它发送它有什么,并开始与翻译的新块&-值.因此,您可能需要在树中组合连续的文本节点以获取整个值.
| 归档时间: |
|
| 查看次数: |
12709 次 |
| 最近记录: |