I have something similar to the following XML document, called sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns:test='www.test.com' xmlns:test2='www.test2.com'>
<test:items>
<test2:item>Some information</test2:item>
</test:items>
</package>
I would like to use Python (2.7) to extract a dictionary of the namespaces as below:
>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('sample.xml')
>>> namespaces = {} # This is the dictionary I want to populate
Required output of code:
>>> namespaces
{'test':'www.test.com', 'test2':'www.test2.com'}
I have read the documentation for ElementTree
but haven't got anywhere yet. Any help much appreciated
If you swap the standard library's xml
for the near-identical but more powerful lxml
, then it's as simple as
import lxml.etree as ET
tree = ET.parse('sample.xml')
namespaces = tree.nsmap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With