Blame view

src/com/ectrip/cyt/exceptionsave/xml/ElementUtils.java 2.4 KB
3c2353cd   杜方   1、畅游通核销app源码提交;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
  package com.ectrip.cyt.exceptionsave.xml;
  
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.List;
  
  import org.dom4j.Attribute;
  import org.dom4j.Element;
  import org.dom4j.Node;
  
  public class ElementUtils {
  
  	private ElementUtils(){};
  
  	public interface ElementExcute{
  		void nextElement(Element e);
  		void elementFinsh();
  	}
  
  	public interface AttributeExcute{
  		void nextAttribute(Element e);
  		void AttributeFinsh();
  	}
  	/** 枚举所有子节点
  	 * @param root 根节点
  	 * @param excute 回调接口
  	 */
  	public static void getElement(Element root,ElementExcute excute) {
  
  		for (Iterator i = root.elementIterator(); i.hasNext();) {
  			Element element = (Element) i.next();
  			excute.nextElement(element);
  		}
  
  		excute.elementFinsh();
  	}
  
  	/**
  	 * 枚举名称为foo的节点
  	 * @param root 根节点
  	 * @param excute 回调接口
  	 * */
  	public static void getElement(Element root, String foo,ElementExcute excute) {
  
  		// 枚举名称为foo的节点
  		for (Iterator i = root.elementIterator(foo); i.hasNext();) {
  			Element child = (Element) i.next();
  			excute.nextElement(child);
  		}
  		excute.elementFinsh();
  	}
  	/**
  	 * 枚举Element的节点的所有属性
  	 * @param root 根节点
  	 * @param excute 回调接口
  	 * */
  	public static void getAttribute(Element root,AttributeExcute attributeExcute) {
  
  		// 枚举属性
  		for (Iterator i = root.attributeIterator(); i.hasNext();) {
  			Attribute attribute = (Attribute) i.next();
  			attributeExcute.AttributeFinsh();
  		}
  	}
  
  
  	/**
  	 * 获得Element的节点的xPath的路径值
  	 * @param root 根节点
  	 * @param strpath xPath路径
  	 * */
  	public static String getPathText(Element root, String strpath) {
  		String result = null;
  		try {
  			Node xpath = (Node) root.selectObject(strpath);
  			result = xpath.getText();
  		} catch (Exception e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		}
  		return result;
  	}
  
  	/**
  	 * 打印所有节点的值和属性
  	 * */
  	public static void println(Element root) {
  		if (root == null)
  			return;
  		// 获取属性
  		@SuppressWarnings("unchecked")
  		List<Attribute> attrs = root.attributes();
  		if (attrs != null && attrs.size() > 0) {
  			for (Attribute attr : attrs) {
  				System.err.print(attr.getValue() + " ");
  			}
  			System.err.println();
  		}
  		// 获取他的子节点
  		List<Element> childNodes = root.elements();
  		for (Element e : childNodes) {
  			println(e);
  		}
  	}
  
  }