Python lxml (objectify): Xpath troubles

╄→гoц情女王★ 提交于 2019-12-11 08:25:37

问题


I am attempting to parse an xml document, extracting data using lxml objectify and xpath. Here is a snip of the document:

<?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>

I have the following method:

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)

...which calls this method:

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

The print statement is from testing. When i execute the first method, it parses through the xml document, successfully stopping at each asset object. I have a dict of variables for it to find, and a complimentary dict of paths for it to use, as defined here:

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'}

However, xpath doesn't seem to be working when I call it on the node (which is an objectified xml node). It just outputs [ ] if I equate it directly, and it gives an index out of range error if I try: [0].text.

What is going on here?


回答1:


/pos/x and /pos/y are absolute XPath expressions and they don't select any element because the provided XML document doesn't have a pos top element.

Try:

pos/x

and

pos/y


来源:https://stackoverflow.com/questions/5467468/python-lxml-objectify-xpath-troubles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!