复制代码
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
# coding=UTF-8
import xml.etree.ElementTree as ET
import traceback
#封装自己的xml解析工具类
#创建时传入文件路径
#根据传入的XPath表达式获取结果,返回集合
class XML:
def __init__(self,path):
self.path = path
try:
#根节点
self.root = ET.parse(self.path)
except:
print u'待解析文件加载异常,未找到根节点'+traceback.print_exc()
self.root = None
def getElementText(self,xpath):
result = None
if self.root is not None:
try:
element = self.root.find(xpath)
result = element.text
except:
print u'未找到对象'+xpath
traceback.print_exc()
return result
def getElementAttrib(self,xpath,attr_name):
result = None
if self.root is not None:
try:
element = self.root.find(xpath)
result = element.attrib[attr_name]
except:
print u'未找到对象'+xpath
traceback.print_exc()
return result
# def getElements(self,xpath):
# if self.root is not None:
# try:
# elements = self.root.findall(xpath)
# result = []
# for element in elements:
# return result.append(element)
# except:
# print u'未找到对象'+xpath
# traceback.print_exc()
最后
以上就是整齐蜜粉最近收集整理的关于xml类的封装的全部内容,更多相关xml类内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复