Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python. how to get attribute value with libxml2

Tags:

python

xml

get

I was using MINIDOM but it does not provide xpath methods.

I am now trying to use libxml2 but I am having trouble retrieving attribute values.

An extract of my xml looks as follow:

<Class name="myclass1" version="0">
    <Owner user-login="smagnoni"/>
</Class>

and I wrote the following code:

import libxml2
doc = libxml2.parseFile(file)
ris = doc.xpathEval('*/Class[@name="'+className+'" and @version="'+classVersion+'"]/Owner')
print str(ris[0])

which returns:

<Owner user-login="smagnoni"/>

How do I get just "smagnoni"? Parsing the string by hand feels overworked. but I did not find a method comparable to .getAttribute("attribute-name") in minidom.

Can anyone suggest the proper method or direct me to documentation?

like image 467
Stefano Avatar asked Jul 22 '11 14:07

Stefano


2 Answers

.prop('user-login') should work:

import libxml2
import io
content='''\
<Class name="myclass1" version="0">
    <Owner user-login="smagnoni"/>
</Class>
'''
doc = libxml2.parseMemory(content,len(content))
className='myclass1'
classVersion='0'
ris = doc.xpathEval('//Class[@name="'+className+'" and @version="'+classVersion+'"]/Owner')

elt=ris[0]
print(elt.prop('user-login'))

yields

smagnoni
like image 175
unutbu Avatar answered Sep 30 '22 03:09

unutbu


for owner in ris:
    for property in owner.properties:
        if property.type == 'attribute':
            print property.name
            print property.content
like image 34
agf Avatar answered Sep 30 '22 04:09

agf