We should think of data formats in terms of different ways of providing structure and consistency to present the data.
->XML - Python natively supports XML encoding and decoding. Parsing XML data is not straight forward way when compared to YAML and JSON.
The simplest way is to parse the XML file is to convert it to ordered dictionary using xmltodict module. Ordered dictionary is a subclass of dictionary in Python and it is used because it remembers the order of how the keys are inserted in to dictionary.
Example:
XML file:
<?xml version="1.0"?>
<device>
<hostname>Edge1</hostname>
<interface>
<name>Ethernet0</name>
<description>L2 Uplink</description>
<enabled>true</enabled>
</interface>
</device>
Install xmltodict module: pip install xmltodict
Python file:
import xmltodict
xmlFile = open ('lab.xml')
xmlData = xmlFile.read()
xmlFile.close()
xml_dict = xmltodict.parse(xmlData)
print(xml_dict)
OrderedDict([('device', OrderedDict([('hostname', 'Edge1'), ('interface', OrderedDict([('name', 'Ethernet0'), ('description', 'L2 Uplink'), ('enabled', 'true')]))]))])
Additional info: link to tutorial how to use xml.etree.ElementTree module:
https://docs.python.org/3.8/library/xml.etree.elementtree.html
All examples are available on my GitHub: https://github.com/lightarchivist/DevNetLabs
No comments:
Post a Comment