Python lxml(对象化): Xpath troubles

标签 python xml xpath lxml objectify

我正在尝试解析 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 文档进行解析,成功地停在每个 Assets 对象上。我有一个变量字典供它查找,还有一个免费的路径字典供它使用,定义如下:

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。

这是怎么回事?

最佳答案

/pos/x/pos/y 是绝对的 XPath 表达式,它们不选择任何元素,因为提供的 XML 文档没有 pos 顶部元素。

尝试:

pos/x

pos/y

关于Python lxml(对象化): Xpath troubles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5467468/

相关文章:

Android更改包名称并且不起作用

java - XML 到 Java 映射工具 - 带有映射描述符

javascript - 值与 xml 元素匹配,然后返回所有兄弟属性值。

python - 在jetson xavier nx上安装python2的llvmlite和numba库

python - 嵌套字典中值的存在

c++ - 从 std::string 中删除所有 xml 标签

python - 使用 Selenium 更改 Google map 评论排序

javascript - 页面刷新后找不到元素 - Selenium

python - 将函数作为字符串获取然后运行它

python - 逐像素读取图像(ndimage/ndarray)