Click here to view code image
import xmltodict
with open("xml_sample.xml") as data:
xml_example = data.read()
xml_dict = xmltodict.parse(xml_example)
>>> print(xml_dict)
OrderedDict([('interface',
OrderedDict([('@xmlns', 'ietf-interfaces'),
('name',
'GigabitEthernet2'), ('description', 'Wide Area
Network'), ('enabled', 'true'),
('ipv4', OrderedDict([('address',
OrderedDict([('ip', '192.168.0.2'), ('netmask',
'255.255.255.0')]))]))]))])
Now that you have the XML in a Python dictionary, you
can modify an element, as shown here:
Click here to view code image
xml_dict["interface"]["ipv4"]["address"]["ip"] =
"192.168.55.3"
You can see your changes in XML format by using the
unparse function (see Example 5-6). You can use the
pretty=True argument to format the XML to make it a
bit easier to read. XML doesn’t care about whitespace,
but humans do for readability.
Example 5-6 Printing from the Command Line with
the unparse Function
Click here to view code image
>>> print(xmltodict.unparse(xml_dict,
pretty=True))
<?xml version="1.0" encoding="utf-8"?>
<interface xmlns="ietf-interfaces">
<name>GigabitEthernet2</name>
<description>Wide Area
Network</description>
<enabled>true</enabled>
<ipv4>