做自动化测试的人,都应该对XPATH很熟悉了,但是在用JAVA解析XML时,我们通常是一层层的遍历进去,这样的代码的局限性很大,也不方便,于是我们结合一下XPATH,来解决这个问题。
所需要的JAR包:
dom4j.jar
jaxen.jar
xmlbeans.jar
具体的代码如下:
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
|
public
class ParseXml { private
String filePath; private
Document document; public
ParseXml(String filePath) { this .filePath = filePath; this .load( this .filePath); }
private
void load(String filePath){ File file =
new File(filePath); if
(file.exists()) { SAXReader saxReader =
new SAXReader(); try
{ document = saxReader.read(file); }
catch (DocumentException e) {
System.out.println( "文件加载异常:"
+ filePath); } }
else { System.out.println( "文件不存在 : "
+ filePath); }
}
public
Element getElementObject(String elementPath) { return
(Element) document.selectSingleNode(elementPath); }
@SuppressWarnings ( "unchecked" ) public
List<Element> getElementObjects(String elementPath) { return
document.selectNodes(elementPath); } @SuppressWarnings ( "unchecked" ) public
Map<String, String> getChildrenInfoByElement(Element element){ Map<String, String> map =
new HashMap<String, String>(); List<Element> children = element.elements(); for
(Element e : children) { map.put(e.getName(), e.getText()); } return
map; } public
boolean isExist(String elementPath){ boolean
flag = false ; Element element =
this .getElementObject(elementPath); if (element !=
null ) flag =
true ; return
flag; } public
String getElementText(String elementPath) { Element element =
this .getElementObject(elementPath); if (element !=
null ){ return
element.getText().trim(); } else { return
null ; }
} public
static void
main(String[] args) { ParseXml px =
new ParseXml( "config/TestBaidu.xml" ); List<Element> elements = px.getElementObjects( "/*/testUI" ); } } |