我正在尝试解析xml文档,使用lxml objectify和xpath提取数据。以下是该文件的摘要:
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset name="Adham">
<pos>
<x>27913.769923</x>
<y>5174.627773</y>
</pos>
<description>Ba bla bla</description>
<bar>(null)</bar>
</general>
</asset>
<asset name="Adrian">
<pos>
<x>-179.477707</x>
<y>5286.959359</y>
</pos>
<commodities/>
<description>test test test</description>
<bar>more bla</bar>
</general>
</asset>
</Assets>
我有以下方法:
def getALLattributesX(self, _root):
'''Uses getattributeX and parses through the attribute dict, assigning
values as it goes. _root is the main document root'''
for k in self.attrib:
self.getattributeX(_root, self.attribPaths[k], k)
...调用此方法:
def getattributeX(self, node, x_path, _attrib):
'''Gets a value from an xml node indicated by an xpath
and assigns it to a the appropriate. If node does not exists
it assigns "error"
'''
print node.xpath(x_path)[0].text
try:
self.attrib[_attrib] = node.xpath(x_path)
except KeyError:
self.misload = True
#except AttributeError:
# self.attrib[attrib] = "error loading " + attrib
#self.misload = True
print语句来自测试。当我执行第一个方法时,它会解析xml文档,成功停止在每个资产对象上。我有一个变量的字典可供查找,还有一个免费的路径供它使用,如下所示:
class tAssetList:
alist = {} #dict of assets
tlist = []
tree = None # XML tree
root = None #root elem
def readXML(self, _filename):
#Load file
fileobject = open(_filename, "r") #read-only
self.tree = objectify.parse(fileobject)
self.root = self.tree.getroot()
for elem in self.root.asset:
temp_asset = tAsset()
a_name = elem.get("name") # get name, which is the key for dict
temp_asset.getALLattributesX(elem)
self.alist[a_name] = temp_asset
class tAsset(obs.nxObject):
def __init__(self):
self.attrib = {"X_pos" : None, "Y_pos" : None}
self.attribPaths = {"X_pos" : '/pos/x', "Y_pos" : '/pos/y'}
但是,当我在节点上调用它时,xpath似乎不起作用(这是一个客观化的xml节点)。如果我直接将它等同,它只输出[]如果我尝试:[0] .text。
它会给出索引超出范围错误这里发生了什么?
答案 0 :(得分:4)
/pos/x
和/pos/y
是绝对的XPath表达式,它们不会选择任何元素,因为提供的XML文档没有pos
顶部元素。
<强>尝试强>:
pos/x
和
pos/y