finding element by tag in xml

Dj Gilcrease digitalxero at gmail.com
Sat Feb 20 22:56:09 CET 2010


On Sat, Feb 20, 2010 at 9:27 AM, sWrath swrath <swrath at gmail.com> wrote:
> from xml.dom.minidom import parse
> from xml.etree.ElementTree import*
>
> file1="book.xml"
> tmptree=ElementTree()
> tmptree.parse(file1)
> items=root.getiterator()
>
>
> dom = parse(file1)
>
>
> #Find tag names
> for node in items :
>    if node.tag == 'author': #Get tag
>        print dom.getElementsByTagName ('book') #Error 1

You are mixing two different types of xml parsers, either user minidom

for node in dom.getElementsByTagName('author'):
    print node.getElementsByTagName('book')

or use etree

for el in items:
    if el.tag == 'author':
        print el.find('book')

There are a few differences you need to note, the getElementsByTagName
always returns a list even if there is only 1 element and find only
returns the first element found no matter what. If you want to print
all books associated with an author you would need to do something
like

for author in tmptree.getiterator('author'):
    for book in author.getiterator('book'):
        print book



More information about the Python-list mailing list