java非递归实现Xml的遍历(多叉树遍历)

来源:互联网 发布:excel防止数据粘贴 编辑:程序博客网 时间:2024/06/06 15:54

import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Stack;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



public class XMLDocParser2 {
Stack<Element> a = null;//栈
private HashMap<String,Element> map = new HashMap<String,Element>();// <Element Name,Element>

 //保存除根节点之外的所有节点

         public void parseXml(String xmlContent) throws Exception{

         SAXReader reader = new SAXReader();
         Document doc;
         java.io.BufferedInputStream is =null;
         try
         {
             is = new java.io.BufferedInputStream(new java.io.ByteArrayInputStream(xmlContent.getBytes("UTF-8")));
             doc = reader.read(is);
             Element root = doc.getRootElement();
             getLeafNodes(root);
         }catch (DocumentException e){
             e.printStackTrace();
         }finally{
          try {
          if(is!=null){
          is.close();
          }
} catch (IOException e) {
e.printStackTrace();
}
         } 
}
 
 private void getLeafNodes(Element rootNode){
 a = new Stack<Element>();
 //将根节点压入栈
 a.push(rootNode);

 if(rootNode.elements().size()==0||rootNode.elements()==null){
 System.out.println("根节点没有子节点");
 }
 Element e = null;//e表示当前栈顶元素
 while(!a.empty()){
    e = a.peek();//获取栈顶元素
  a.pop();//将栈顶元素出栈
          String elementTag = e.getName();

         map.put(elementTag,xmle);

   List list = e.elements();

  int size = e.elements().size();

         //对栈顶元素进行反向遍历,入栈

  for(int i= size-1;i>=0;i--){
  a.push((Element)e.elements().get(i));
  }
 }
 }

public static void main(String[] args) throws Exception {
String xml="<html><head></head><body><mm>123</mm><oo>xxx</oo><nn>123456</nn></body></html>";
      XMLDocParser2 a = new XMLDocParser2();
a.parseXml(xml);
}
}
0 0
原创粉丝点击