XML ElementTree Parse.

Fredrik Lundh fredrik at pythonware.com
Thu Oct 12 06:20:36 EDT 2006


marc.wyburn at googlemail.com wrote:

> I'm playing with XML and elementtree and am missing something but I'm
> not sure what...? I've create an XML file with Elementtree with a root
> of backup.xml.  Attached to the root is a dirob and the dirobj has a
> fileobj.  fileobj has filename and filesize tags.  I can open the file
> in excel and it sets out the columns as I would expect.  The problem
> I'm having is parsing the file. Using..
>
>>>> file = open('c:\\scripts\\backup.xml', "r")
>>>> tree = parse(file)
>>>> elem = tree.getroot()
>>>> elem.findtext('filesize')
>
> Doesn't return anything, infact I can't seem to find anything
> regardless of what I search for.

find/findtext/findall only look at direct subelements, unless you use xpath-
style syntax.  in this case,

    elem.findtext("dirob/fileob/filesize")

should do the trick.  or you could do something like

    for dir_elem in tree.findall("dirob"):
        for file_elem in dirob.findall("fileob"):
            print file_elem.findtext("filesize")

to loop over all directory objects at the top level, and print the sizes for
all files in those directories.

to get the first filesize in the tree, no matter where it is, use

    elem.findtext(".//filesize")

</F>

> - <backup.xml>
> -  <dirob>
>     <dirname>C:\sysprep</dirname>
> -  <fileob>
>      <filename>test.txt</filename>
>      <filesize>10</filesize>
>     </fileob>
>    </dirob>
>  </backup.xml>






More information about the Python-list mailing list