no_freedom
no_freedom

Reputation: 1961

Print XML tag attributes using element tree

I'm using following statements to print the value of Title tag. Its working fine. But I'm also want to print <page id='...' ....... Is it possible? thanks

            <mediawiki>
          <siteinfo>
            <sitename>Wiki</sitename>
            <namespaces>
              <namespace key="-2" case="first-letter">Media</namespace>
            </namespaces>
          </siteinfo>
        <page id="31239628" orglength="6822" newlength="4524" stub="0" categories="0" outlinks="1" urls="10">
        <title>Title</title>
        <categories></categories>
        <links>15099779</links>
        <urls>
        </urls>
        <text>

        Books

        </text>
        </page>

        </mediawiki>

Here is my working code. Which print the title tag values.

import xml.etree.cElementTree as etree
tree = etree.parse('find_title.xml')
for value in tree.getiterator(tag='title'):
    print value.text

Upvotes: 1

Views: 2098

Answers (1)

aayoubi
aayoubi

Reputation: 12109

You can try the following:

import xml.etree.cElementTree as etree
from pprint import pprint
tree = etree.parse('find_title.xml')
for value in tree.getiterator(tag='title'):
    print value.text
for value in tree.getiterator(tag='page'):
    pprint(value.attrib)

It should output something like this:

$ python file.py
Title
{'categories': '0',
 'id': '31239628',
 'newlength': '4524',
 'orglength': '6822',
 'outlinks': '1',
 'stub': '0',
 'urls': '10'}

Upvotes: 2

Related Questions