XML parsing specific values - Python -


i've been attempting parse list of xml files. i'd print specific values such username value.

<?xml version="1.0" encoding="utf-8"?> <drives clsid="{8fddcc1a-0c3c-43cd-a6b4-71a6df20da8c}"          disabled="1">   <drive clsid="{935d1b74-9cb8-4e3c-9914-7dd559b7a417}"           name="s:"           status="s:"           image="2"           changed="2007-07-06 20:57:37"           uid="{4da4a7e3-f1d8-4fb1-874f-d2f7d16f7065}">     <properties action="u"                  thisdrive="nochange"                  alldrives="nochange"                  username=""                  cpassword=""                  path="\\scratch"                  label="scratch"                  persistent="1"                  useletter="1"                  letter="s"/>   </drive> </drives> 

my script working fine collecting list of xml files etc. below function print relevant values. i'm trying achieve suggested in post. i'm doing incorrectly i'm getting errors suggesting elm object has no attribute text. appreciated.

current code

from lxml import etree et  def read_files(files):     fi in files:         doc = et.parse(fi)         elm = doc.find('username')         print elm.text 

doc.find looks tag given name. looking attribute given name.

elm.text giving error because doc.find doesn't find tags, returns none, has no text property.

read lxml.etree docs more, , try this:

doc = et.parse(fi) root = doc.getroot() prop = root.find(".//properties") # finds first <properties> tag anywhere elm = prop.attrib['username'] 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

django - CSRF verification failed. Request aborted. CSRF cookie not set -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -