我正在使用 xpath 读取一个 xml 文件,它返回 null 的问题。
主要的.py
#!/usr/bin/python
import sys
from util import xml_util
def main():
try:
xml = XMLReader('test.xml')
x = xml.getitem('numbers/x')
print x
return 0
except:
return -1
if __name__ == '__main__':
sys.exit(main())
xml_util.py
from lxml import etree
class XMLReader:
"Parse file and read data using find(path)"
def __init__(self,fname):
self.tree = etree.parse(fname)
self.root = self.tree.getroot()
def getitem(self,path,converter=str):
return converter(self.root.find(path).text)
def getlist(self,path,converter=str):
return [converter(item.text) for item in self.root.find(path)]
测试.xml
<mystuff>
<numbers>
<x>3.14</x>
<y>42</y>
<z>11</z>
</numbers>
</mystuff>
XMLReader 类是从这篇文章https://stackoverflow.com/questions/4357494/how-do-i-read-data-using-lxml-in-python