Python Forum
How to display XML tree structure with Python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to display XML tree structure with Python?
#6
Pretty straight away:

from lxml import etree
from collections import Counter

xml = '''\
<data>
    <timestamp>...</timestamp>
    <people>
        <person>
            <name>...</name>
            <age>...</age>
        </person>
        <person>
            <name>...</name>
            <age>...</age>
            <degree />
        </person>
        <person>
            <name>...</name>
            <age>...</age>
            <degree />
            <siblings>
                <brother>...</brother>
                <brother>...</brother>
                <sister>...</sister>
            </siblings>
        </person>
    </people>
    <cities>
        <city>
            <name>...</name>
            <country>...</country>
            <continent>...</continent>
            <capital />
        </city>
        <city>
            <name>...</name>
            <country>...</country>
            <continent>...</continent>
        </city>
    </cities>
</data>
'''

root = etree.fromstring(xml)

for tag in root.iter():
    path = tree.getpath(tag)
    path = path.replace('/', '    ')
    spaces = Counter(path)
    tag_name = path.split()[-1].split('[')[0]
    tag_name = ' ' * (spaces[' '] - 4) + tag_name
    print(tag_name)
Output:
data     timestamp     people         person             name             age         person             name             age             degree         person             name             age             degree             siblings                 brother                 brother                 sister     cities         city             name             country             continent             capital         city             name             country             continent
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
RE: How to display XML tree structure with Python? - by wavic - Nov-10-2017, 08:43 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Web app structure with python as backend alt19 1 2,000 Oct-06-2020, 11:28 PM
Last Post: scidam
  Cant set api response as tree in Element tree hey_arnold 4 3,736 Mar-04-2019, 03:25 PM
Last Post: dsarin

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020