Sunday, 3 October 2021

DevNet - XML - Parsing Data Formats in Python

 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)



Output after running Python script:


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

Plumbing... QoS

Rule no 1. QoS does not help in situations where there is no enough bandwidth but helps optimize performance by prioritization of the traffi...