Python. how to get attribute value using libxml2

I used MINIDOM, but it does not provide xpath methods.

Now I'm trying to use libxml2, but it's hard for me to get the attribute values.

My xml extract is as follows:

<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 only smagnoni? Parsing a string manually seems like overworked work. but I did not find a method comparable to .getAttribute("attribute-name") in the minidom.

Can someone suggest the right method or direct me to the documentation?

+7
source share
3 answers
 for owner in ris: for property in owner.properties: if property.type == 'attribute': print property.name print property.content 
+3
source

.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')) 

gives

 smagnoni 
+4
source

lxml uses libxml2 and provides a more user-friendly interface ( ElementTree api ), so you get the most from the speed of libxml2 and all the benefits of this xpath evaluation.

 import lxml.etree as ET doc = ET.parse(file) owner = doc.find('/*/Class[@name="'+className+'" and @version="'+classVersion+'"]/Owner') if owner: print owner.get('user-login') 

The added bonus is that the Element api is by default available in python2.5 (although version 1.5 does not include the xpath [@name='value'] syntax that was added in python 2.7, but you can get 1.3 api as separate package in older versions of python version 2.x.

You can import any compatible version of Apache ElementTree using:

 try: from lxml import etree print("running with lxml.etree") except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: try: # Python 2.5 import xml.etree.ElementTree as etree print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree print("running with ElementTree") except ImportError: print("Failed to import ElementTree from any known place") 
+2
source

All Articles