Dom4j解析xml中的各个节点的属性值

Dom4j是比较常见的xml解析方式,适用于小型文档。

优点:

1.能够获取和操作任意部分的数据。

2.允许应用程序对数据和结构做出更改。

3.可随机访问xml。

缺点:

需要装载整个xml,消耗资源大,解析速度慢(解析是需要生成节点树,在内存中生成树比较耗时)。

解析

1.下载相关Dom4j的的jar包

2.

public class Dom4jClass {
	public static void main(String args[]) throws Exception{
		//创建一个SAXReader对象
       SAXReader sax = new SAXReader();
       //读取需要解析的xml文件
       File xmlFile = new File("E:\\云检测/xml试验数据格式/充电阶段测试.xml");
       //获取document对象
       Document document = sax.read(xmlFile);
       //获取根节点rootElement
       Element rootElement = document.getRootElement();
       nodeValue(rootElement);
	}
	public static void nodeValue(Element rootElement){
		 //获取节点下的所有属性listAttr
		 List listAttr=rootElement.attributes();
		 //遍历所有属性
	       for(Attribute attr : listAttr){
	    	   //属性名称
	    	   String name = attr.getName();
	    	   //属性值
	    	   String value = attr.getValue();
	    	   System.out.println("节点名:"+name+" 节点值:"+value);
	       }
	       //获取当前节点的所有子节点
	       List listelement = rootElement.elements();
	       //遍历所有子节点
		      for(Element e : listelement){
		    	  //调用nodeValue方法
		    	  nodeValue(e);
		      }
	}
}

猜你喜欢

转载自blog.csdn.net/Dwayne_Wei/article/details/78026709