用DOM4j解析xml文件,获得所有节点信息

对于一个xml文件,将其所有信息节点提取出来,这里我采用广度优先搜索算法。程序如下:

 

//读取文件 public Document read(String fileName)throws MalformedURLException, DocumentException{ SAXReader reader = new SAXReader(); Document document = reader.read(fileName); return document; }

 

//采用广度优先算法进行解析 public void output(Document doc){ Element root = doc.getRootElement(); List<Element> list = new ArrayList<Element>(); list.add(root); while(list != null){ Element element = null; Element ele = null; Iterator ite = list.iterator(); if(ite.hasNext()){ ele = (Element) ite.next(); ite.remove(); } if(ele != null){ for(Iterator i = ele.elementIterator();(i != null)&& (i.hasNext());){ element = (Element) i.next(); list.add(element); if(element != null) System.out.println(element.getName()+" : "+element.getPath()+" --"+ element.getText()); } } } }

你可能感兴趣的:(xml,算法,list,null,iterator,output)