8
8
import java .util .List ;
9
9
import java .util .Map ;
10
10
11
- import org .dom4j .Attribute ;
12
11
import org .dom4j .Document ;
13
- import org .dom4j .DocumentException ;
14
12
import org .dom4j .Element ;
15
13
import org .dom4j .io .SAXReader ;
16
14
19
17
* @author ren
20
18
*
21
19
*/
22
- public class Dom4jParseXmlUtil {
20
+ public class Dom4jUtil {
23
21
24
22
/**
25
- * 获取根节点
26
- * @param path
27
- * @return Element
23
+ * 传入文件路径解析xml文件获取根节点
24
+ * @param path xml文件的绝对路径
25
+ * @return Element 根节点
28
26
*/
29
27
public static Element parseXml (String path ){
30
28
InputStream is = null ;
@@ -38,9 +36,12 @@ public static Element parseXml(String path){
38
36
//获取根节点对象
39
37
Element rootElement = document .getRootElement ();
40
38
return rootElement ;
41
- } catch (FileNotFoundException | DocumentException e ) {
39
+ } catch (FileNotFoundException e ) {
42
40
e .printStackTrace ();
43
- }finally {
41
+ } catch (Exception e ) {
42
+ e .printStackTrace ();
43
+ }
44
+ finally {
44
45
if ( is !=null ){
45
46
try {
46
47
is .close ();
@@ -68,23 +69,33 @@ public static Map<String, String> getAttribute(Element element){
68
69
return map ;
69
70
}
70
71
71
- public static void getNode (Element element ){
72
+ /**
73
+ * 根据传入的Action名返回结果JSP
74
+ * @param element 根节点
75
+ * @param actionName 标签name属性的value
76
+ * @return map 封装返回结果jsp的map对象
77
+ */
78
+ public static Map <String , String > getJspMap (Element element ,String actionName ){
79
+ Map <String , String > map = new HashMap <String , String >();
72
80
List <Element > actions = element .elements ();
73
81
for (Element action : actions ) {
74
- List <Element > results = action .elements ();
75
- for (Element result : results ) {
76
- String name = result .attributeValue ("name" );
77
- String text = result .getText ();
78
- System .out .println (name +":" +text );
82
+ if (actionName .equals (action .attributeValue ("name" ))){
83
+ List <Element > results = action .elements ();
84
+ for (Element result : results ) {
85
+ String name = result .attributeValue ("name" );
86
+ String text = result .getText ();
87
+ map .put (name , text );
88
+ }
79
89
}
80
90
}
91
+ return map ;
81
92
}
82
93
83
94
public static void main (String [] args ) {
84
- String path = Dom4jParseXmlUtil .class .getResource ("" ).getPath ()+"struts.xml" ;
95
+ String path = Dom4jUtil .class .getResource ("" ).getPath ()+"struts.xml" ;
85
96
System .out .println (path );
86
97
Element element = parseXml (path );
87
98
Map <String , String > attribute = getAttribute (element );
88
- getNode ( element );
99
+ System . out . println ( getJspMap ( element , "login" ). get ( "success" ) );
89
100
}
90
101
}
0 commit comments