做自动化测试的人,都应该对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"); } } |

本文介绍了一种利用XPath与Java结合的方式解析XML文件的方法。通过使用dom4j、jaxen及xmlbeans等库,文章提供了一个名为ParseXml的类,该类能够实现对XML文件的读取、定位元素路径、获取元素文本等功能。
2421

被折叠的 条评论
为什么被折叠?



