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?
#5
Just getting name of tags work fine in both lxml and BeautifulSoup.
Keeping the structure in output can be a challenge,
as both pretty print()lxml and prettify()BS i do not think work for text output.

Example getting tag names:
from lxml import etree
from bs4 import BeautifulSoup

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)
soup = BeautifulSoup(xml, 'lxml')

# lxml
for node in root.iter('*'):
    print(node.tag)

# BS
for tag in soup.findChildren():
    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
Reply


Messages In This Thread
RE: How to display XML tree structure with Python? - by snippsat - Nov-10-2017, 06:54 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Web app structure with python as backend alt19 1 2,016 Oct-06-2020, 11:28 PM
Last Post: scidam
  Cant set api response as tree in Element tree hey_arnold 4 3,776 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