import xml.etree.ElementTree as ET

tree = ET.parse("country_data.xml")
root = tree.getroot()


for child in root:
    print(child.tag, child.attrib)


print(root.tag)
print(root.attrib)
print(root[0][1].text)


for neighbor in root.iter("neighbor"):
    print(neighbor.attrib)


for country in root.findall("country"):
    rank = country.find("rank").text
    name = country.get("name")
    print(name, rank)


for rank in root.iter("rank"):
    new_rank = int(rank.text) + 1
    rank.text = str(new_rank)
    rank.set("updated", "yes")

tree.write("output1.xml")


for country in root.findall("country"):
    # using root.findall() to avoid removal during traversal
    rank = int(country.find("rank").text)
    if rank > 50:
        root.remove(country)

tree.write("output2.xml")


import xmltodict

with open("output3.xml") as fd:
    doc = xmltodict.parse(fd.read())

doc["mydocument"]["@has"]  # == u'an attribute'
doc["mydocument"]["and"]["many"]  # == [u'elements', u'more elements']
doc["mydocument"]["plus"]["@a"]  # == u'complex'
doc["mydocument"]["plus"]["#text"]  # == u'element as well'


# https://docs.python.org/3/library/xml.etree.elementtree.html
