Python lxml (objectify): Xpath问题
我正在尝试解析一个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
打印语句是用来测试的。当我执行第一个方法时,它会遍历整个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'}
但是,当我在节点(这是一个被对象化的xml节点)上调用xpath时,它似乎不起作用。如果我直接进行比较,它只输出[ ],而如果我尝试使用[0].text,就会出现索引超出范围的错误。
这是怎么回事呢?
1 个回答
4
/pos/x
和 /pos/y
是绝对的XPath表达式,但它们没有选择到任何元素,因为提供的XML文档里没有一个叫做 pos
的顶层元素。
尝试一下:
pos/x
和
pos/y