Do you know XML data is the prime data you need to work with in real-time projects? Here are the easy ways to work with XML data and files in Python. In the first case, you can obtain the specific value by reading XML, and you get a value by reading the XML file in the second case.

Easy Ways to Work With XML Files: Python
Photo by Anindita Chatterjee on Pexels.com

This Python code demonstrates two methods for reading XML data, directly from a string and from a file. These methods showcase how to extract specific information from XML data using Python’s ElementTree module.

1. XML Data as input

The first method uses an XML string as input. It starts by importing the `xml.etree.ElementTree` module as `ET`. The XML data is then assigned to a variable called `xml_data`. The `ET.fromstring` method is used to parse the XML data and obtain the root element. The code then extracts specific values from the XML using the `find` method, and appends them to a list called `forms_and_descs`. The extracted values are printed as “To” and “Heading”.

import xml.etree.ElementTree as ET

xml_data = '''
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
'''

root = ET.fromstring(xml_data)

forms_and_descs = []
for item in root.findall("."):  # Change the search path to "."
    form = item.find("to")
    head = item.find("heading")
    forms_and_descs.append((form.text, head.text))

for form, head in forms_and_descs:
    print("To:", form)
    print("Heading:", head)

Output

To: Tove
Heading: Reminder

2. XML File as input

The second method involves reading an XML file. It also imports the `xml.etree.ElementTree` module and uses the `ET.parse` method to parse the XML file. The root element is obtained using the `getroot` method. The code then extracts author and title information from each ‘book’ element and appends them to a list called `auth_title`, which is subsequently printed.

import xml.etree.ElementTree as ET

tree=ET.parse("/content/BOOKS.xml")

root=tree.getroot()

auth_title=[]
for item in root.findall('./book'):
  author=item.find("author")
  title=item.find("title")
  if author is not None and title is not None:
    auth_title.append((author.text, title.text))

print(auth_title)

Conclusion

  • In this tutorial, we explored two easy methods for working with XML data and files in Python. The first method uses an XML string as input, while the second program reads an XML file. With xml.etree.ElementTree module, we were able to parse the XML data and extract specific information using Python’s powerful functionalities. These are useful in dealing with XML data.
  • By mastering these methods, developers can efficiently handle XML data and leverage the flexibility and power of Python. If it’s extracting specific values from XML or parsing XML files, the examples provided here offer a solid foundation for working with XML in Python.
  • To your practice, refer to the sample XML file and consider delving into the book “Mastering Python Programming” for a comprehensive understanding of Python’s capabilities in handling XML data.

References