4

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.