我试图获取 XML 文件的所有元素并使用递归方法将其放入 ArrayList>>,但出现错误:java.util.ArrayList 处的线程“main”java.lang.StackOverflowError 中的异常。当我进行递归调用时出现错误:GetAllXml(ListTree);
我想得到这样的结构 [[[un]] , [[deux,trois,quatre]] , [[cinq,six,sept],[huit,noeuf],[dix,onze]]] 这里是我的代码:
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class esperant {
/**
* @param args
*/
private static List<Element> getChildren(Node parent)
{
NodeList nl = parent.getChildNodes();
List<Element> children = new ArrayList<Element>(nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element)
children.add((Element) n);
}
return children;
}
public static void GetAllXml(ArrayList<ArrayList<ArrayList<Element>>> ListTree)
{
ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
int level = ListTree.size()-1;
for (int i=0;i<ListTree.get(level).size();i++)
{
for (int j=0;j<ListTree.get(level).get(i).size();j++)
{
ArrayList<Element> childOfChild = new ArrayList<Element>();
childOfChild.addAll(getChildren(ListTree.get(level).get(i).get(j)));
child.add(childOfChild);
}
}
ListTree.add(child);
GetAllXml(ListTree);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ArrayList<ArrayList<Element>>> ListTree = new ArrayList<ArrayList<ArrayList<Element>>>();
ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
ArrayList<Element> childOfChild = new ArrayList<Element>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse("test.xml");
Element root = doc.getDocumentElement();
childOfChild.add(root);
child.add(childOfChild);
ListTree.add(child);
GetAllXml(ListTree);
System.out.println(ListTree);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
这是xml文件:
<?xml version="1.0" encoding="iso-8859-1"?>
<un>
<deux> <cinq></cinq> <six></six> <sept></sept> </deux>
<trois> <huit></huit><noeuf></noeuf> </trois>
<quatre><dix></dix><onze></onze> </quatre>
</un>