i am reading an xml file using xpath the issue its returning null.
main.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)]
test.xml
<mystuff>
<numbers>
<x>3.14</x>
<y>42</y>
<z>11</z>
</numbers>
</mystuff>
The XMLReader class is received from this post https://stackoverflow.com/questions/4357494/how-do-i-read-data-using-lxml-in-python
Edit
If you’re still haveing problems and you set up a module with
__init__.pyand are trying to import xml_util then reference your readerxml_util.XMLReaderor change your import statment tofrom util.xml_util import XMLReader