xml

What it is good for?

Parse XML files.

The xml module contains several XML parsers. They produce a tree of DOM objects for each tag that can be searched and allow access to attributes.

Installed with Python by default

yes

Example

Sample XML data:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <actor_list>
  3. <actor name="Hamlet">the Prince of Denmark</actor>
  4. <actor name="Polonius">Ophelias father</actor>
  5. </actor_list>

Read an XML file and extract content from tags:

  1. from xml.dom.minidom import parse
  2. document = parse('hamlet.xml')
  3. actors = document.getElementsByTagName("actor")
  4. for act in actors:
  5. name = act.getAttribute('name')
  6. for node in act.childNodes:
  7. if node.nodeType == node.TEXT_NODE:
  8. print("{} - {}".format(name, node.data))
  9. Hamlet - the Prince of Denmark
  10. Polonius - Ophelias father

Where to learn more?

https://docs.python.org/3/library/xml.html