求救:一个遍历XML的程序,竟然出现无限递归,导致StackOverflowError。我觉得算法没有问题!难道Java API 有bug?
XML 片段 如下:(说明:每个节点自身,都有name和value属性。value熟悉肯定没有重复,因为已经在数据库中验证过。)
<?xml version= "1.0 " encoding= "UTF-8 " ?>
<category-config>
<first-level name= "Transportation " value= "2700000000 ">
<second-level name= "Aviation " value= "2701000000 "/>
<second-level name= "Logistics " value= "2708000000 "/>
</first-level>
<first-level name= "Others " value= "2900000000 ">
<second-level name= "Others " value= "2901000000 "/>
</first-level>
</category-config>
程序的思路:根据传递进来的一个节点,及需要找的 value 值,在该节点所代表的子树中找 value 值能匹配的节点。如当前节点匹配,则递归结束,否则,对每个子节点,调用自己。调用结束是,用返回值是否为null表示在当前子树中是否找到(null表示未找到)
该代码如下:
private String recursiveGetNameByValue( Element element, String value) {
// Element 的全类名: org.w3c.dom.Element
String result = null;
if (element.getAttribute( "value ").equals(value)) {
result = element.getAttribute( "name ");
return result;
}
NodeList childNodeList = element.getChildNodes();
int size = childNodeList.getLength();
for (int i = 0; i < size; i++) {
if (childNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element curElement = (Element) childNodeList.item(i);
result = recursiveGetNameByValue(curElement, value); // 此处为递归
if (result != null) {
break;
}
}
} // End of for Loop
return result;
}
这段代码运行了大半年,一直没有出现问题。XML也有一个多月没动过(整个XML在浏览器中显示完全正常,任何节点都可以展开、收缩)。非常奇怪!
报错的片段:(CategoryFactory是上面的方法所在的类名)
java.lang.StackOverflowError
at org.apache.xerces.dom.NamedNodeMapImpl.findNamePoint(Unknown Source)
at org.apache.xerces.dom.NamedNodeMapImpl.getNamedItem(Unknown Source)
at org.apache.xerces.dom.ElementImpl.getAttribute(Unknown Source)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:477)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)
at com.Mycomp.CategoryFactory.recursiveGetNameByValue(CategoryFactory.java:489)