javaee 递归读取xml文件

package com.test.xml;

import java.io.InputStream;
import java.util.Iterator;

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

public class ReadXml2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//1.获得xml文件的流对象(输入流)
		InputStream iStream=  ReadXml.class.getResourceAsStream("/Books.xml");
		//2.创建SAXReader解析器,读取xml文件到dom文档树对象中
		SAXReader saxReader=new SAXReader();
		try {
			Document document=  saxReader.read(iStream);
			
			//获得根节点
			Element root=  document.getRootElement();
			
			readElement(root);
			
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
	}
	
	public static void readElement(Element element)
	{
		//返回当前节点下的子节点组成的集合对应的迭代器
		Iterator<Element> iterator=  element.elementIterator();
		
		//遍历每一个子节点
		while(iterator.hasNext())
		{
			 //读取下一个子节点
			 Element child=  iterator.next();	
			
			 System.out.println(child.getName()+":"+child.getText());
			 
			 //获得节点的属性
			  Iterator<Attribute> attr_iterator=  child.attributeIterator();
			 
			  while(attr_iterator.hasNext())
			  {
				  Attribute attribute=  attr_iterator.next();
				  
				  System.out.println(attribute.getName()+":"+attribute.getText());
			  }
			 
			  //获得节点的子节点
			  readElement(child);			 
		}
	}
	
	

}

你可能感兴趣的:(Mac开发,java-ee,xml,java)