[libvirt-users] Python XML parsing of domain descriptions?

Cole Robinson crobinso at redhat.com
Fri Oct 1 18:20:48 UTC 2010


On 10/01/2010 12:19 PM, Stanley, Jon [Tech] wrote:
> Does anyone know of a way to parse the libvirt XML into usable python data structures? Ideally, it would be something like foo['domain']['devices']['bridge'][0]['target'] or something of the sort. What I'm looking to accomplish is to figure out which tap interface goes with a specific domain.
> 
> I'm not keen on parsing XML to get that mapping, is there a better way to do it without parsing XML?
> 

I don't know of a solution off hand, but googling 'python xml to
dictionary' brings up a few people asking the same question, and some
possible solutions.

That said, just parsing the xml by hand isn't too bad, it only takes a
few minutes to learn how to contruct xpaths for lookup. Here's how to
get the target dev for the first interface device using libxml2 (and as
I understand it, the native python xml libraries are even simpler):


import libxml2

xmlstr = file("myxml.xml").read()
doc = libxml2.parseDoc(xmlstr)
ctx = doc.xpathNewContext()

nodelist = ctx.xpathEval("/domain/devices/interface[1]/target/@dev")
val = nodelist and nodelist[0].content or None
print val

- Cole




More information about the libvirt-users mailing list