🌐
Omz Software
omz-software.com › pythonista › docs › ios › xmltodict.html
xmltodict — Python 3.6.1 documentation
February 19, 2020 - >>> xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a>\"\"\", item_depth=2, item_callback=handle) path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1 path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2 · The optional argument postprocessor is a function that takes path, key and value as positional arguments and returns a new (key, value) pair where both key and value may have changed. Usage example:
🌐
PyPI
pypi.org › project › xmltodict
xmltodict · PyPI
Text values for nodes can be specified ... for attr_prefix is @ and the default value for cdata_key is #text. >>> import xmltodict >>> >>> mydict = { ......
      » pip install xmltodict
    
Published   Feb 22, 2026
Version   1.0.4
🌐
Medium
cihankursun95.medium.com › how-to-parse-xmltodict-and-write-elementtree-xml-with-using-python-33361ca68aba
How to Parse (xmltodict) and Write (ElementTree) XML with Using Python? | by cihan kursun | Medium
May 21, 2022 - I will add the pdb library to get ... xmltodict import pdb with open('example.xml') as fd: doc = xmltodict.parse(fd.read()) pdb.set_trace() print("xml is read")...
🌐
AskPython
askpython.com › home › xmltodict module in python: a practical reference
xmltodict Module in Python: A Practical Reference - AskPython
December 9, 2020 - xmltodict.parse() method takes an XML file as input and changes it to Ordered Dictionary. We can then extract the dictionary data from Ordered Dictionary using dict constructor for Python dictionaries.
🌐
Readthedocs
xmltodict.readthedocs.io › en › stable › README
README - xmltodict
xmltodict is a Python module that makes working with XML feel like you are working with JSON, as in this "spec": >>> print(json.dumps(xmltodict.parse(""" ... <mydocument has="an attribute"> ... <and> ... <many>elements</many> ... <many>more elements</many> ...
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › scenarios › xml
XML parsing — The Hitchhiker's Guide to Python
For example, an XML file like this: <?xml version="1.0"?> <root> <child name="child1"> </root> can be loaded like this: import untangle obj = untangle.parse('path/to/file.xml') and then you can get the child element’s name attribute like this: ...
🌐
The Hitchhiker's Guide to Python
python-docs.readthedocs.io › en › latest › scenarios › xml.html
XML parsing - The Hitchhiker's Guide to Python - Read the Docs
untangle is a simple library which takes an XML document and returns a Python object which mirrors the nodes and attributes in its structure. For example, an XML file like this: <?xml version="1.0"?> <root> <child name="child1"> </root> can be loaded like this: import untangle obj = untangle.parse('path/to/file.xml') and then you can get the child elements name like this: obj.root.child['name'] untangle also supports loading XML from a string or an URL. xmltodict is another simple library that aims at making XML feel like working with JSON.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-xml-to-json-dict
Python XML to JSON, XML to Dict | DigitalOcean
August 3, 2022 - We can directly pick files and convert them to JSON as well. Let’s look at a code snippet how we can perform the conversion with an XML file: import xmltodict import pprint import json with open('person.xml') as fd: doc = xmltodict.parse(fd.read()) pp = pprint.PrettyPrinter(indent=4) ...
🌐
ProgramCreek
programcreek.com › python › example › 82408 › xmltodict.parse
Python Examples of xmltodict.parse
def parse_nmap_xml(nmap_output_file, protocol): targets = [] with open(nmap_output_file, 'r') as file_handle: scan_output = xmltodict.parse(file_handle.read()) for host in scan_output['nmaprun']['host']: if host['address'][0]['@addrtype'] != 'ipv4': continue ip = host['address'][0]['@addr'] for port in host['ports']['port']: if port['state']['@state'] == 'open': if 'service' in port and (port['service']['@name'] in protocol_dict[protocol]['services']): if ip not in targets: targets.append(ip) elif port['@portid'] in protocol_dict[protocol]['ports']: if ip not in targets: targets.append(ip) return targets
Find elsewhere
🌐
GitHub
github.com › martinblech › xmltodict › blob › master › xmltodict.py
xmltodict/xmltodict.py at master · martinblech/xmltodict
"""Parse the given XML input and convert it into a dictionary. · `xml_input` can either be a `string`, a file-like object, or a generator of strings. · If `xml_attribs` is `True`, element attributes are put in the dictionary ·  ...
Author   martinblech
🌐
GitHub
github.com › martinblech › xmltodict
GitHub - martinblech/xmltodict: Python module that makes working with XML feel like you are working with JSON · GitHub
February 16, 2014 - Text values for nodes can be specified ... for attr_prefix is @ and the default value for cdata_key is #text. >>> import xmltodict >>> >>> mydict = { ......
Starred by 5.7K users
Forked by 468 users
Languages   Python
🌐
Snyk
snyk.io › advisor › xmltodict › functions › xmltodict.parse
How to use the xmltodict.parse function in xmltodict | Snyk
""" dir_out_dict = xmltodict.parse(self.device.show('dir', text=True)[1]) dir_out = dir_out_dict['ins_api']['outputs']['output']['body'] match = re.search(r'(\d+) bytes free', dir_out) bytes_free = match.group(1) return int(bytes_free) CiscoDevNet / netprog_basics / network_device_apis / netconf / example2.py View on Github
Top answer
1 of 4
36

Using your example:

import xmltodict

with open('artikelen.xml') as fd:
    doc = xmltodict.parse(fd.read())

If you examine doc, you'll see it's an OrderedDict, ordered by tag:

>>> doc
OrderedDict([('artikelen',
              OrderedDict([('artikel',
                            [OrderedDict([('@nummer', '121'),
                                          ('code', 'ABC123'),
                                          ('naam', 'Highlight pen'),
                                          ('voorraad', '231'),
                                          ('prijs', '0.56')]),
                             OrderedDict([('@nummer', '123'),
                                          ('code', 'PQR678'),
                                          ('naam', 'Nietmachine'),
                                          ('voorraad', '587'),
                                          ('prijs', '9.99')])])]))])

The root node is called artikelen, and there is a subnode artikel which is a list of OrderedDict objects, so if you want the code for every article, you would do:

codes = []
for artikel in doc['artikelen']['artikel']:
    codes.append(artikel['code'])

# >>> codes
# ['ABC123', 'PQR678']

If you specifically want the code only when nummer is 121, you could do this:

code = None
for artikel in doc['artikelen']['artikel']:
    if artikel['@nummer'] == '121':
        code = artikel['code']
        break

That said, if you're parsing XML documents and want to search for a specific value like that, I would consider using XPath expressions, which are supported by ElementTree.

2 of 4
-1

This is using xml.etree You can try this:

for artikelobj in root.findall('artikel'):
    print artikelobj.find('code')

if you want to extract a specific code based on the attribute 'nummer' of artikel, then you can try this:

for artikelobj in root.findall('artikel'):
    if artikel.get('nummer') == 121:
        print artikelobj.find('code')

this will print only the code you want.

🌐
CloudDefense.ai
clouddefense.ai › code › python › example › xmltodict
Top 10 Examples of <!-- -->xmltodict<!-- --> code in Python | CloudDefense.AI
def test_streaming_interrupt(self): cb = lambda path, item: False self.assertRaises(ParsingInterrupted, parse, '<a>x</a>', item_depth=1, item_callback=cb) ... def __list_flows( api_call: str, output_format: str = 'dict' ) -> Union[Dict, pd.DataFrame]: xml_string = openml._api_calls._perform_api_call(api_call, 'get') flows_dict = xmltodict.parse(xml_string, force_list=('oml:flow',)) # Minimalistic check if the XML is useful assert type(flows_dict['oml:flows']['oml:flow']) == list, \ type(flows_dict['oml:flows']) assert flows_dict['oml:flows']['@xmlns:oml'] == \ 'http://openml.org/openml', flows
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-convert-xml-to-dictionary
Python program to convert XML to Dictionary - GeeksforGeeks
July 23, 2025 - xmltodict.parse(xml_input, encoding='utf-8', expat=expat, process_namespaces=False, namespace_separator=':', **kwargs) Use pprint(pretty print) to print the dictionary in well-formatted and readable way. Syntax : pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) Example: Converting XML to dictionary · File Used: Python ·
🌐
Tanium
tanium.github.io › pytan › _modules › xmltodict.html
xmltodict — PyTan v2.1.6 2.1.6 documentation
E.g: >>> import defusedexpat >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat) OrderedDict([(u'a', u'hello')]) """ handler = _DictSAXHandler(namespace_separator=namespace_separator, **kwargs) if isinstance(xml_input, _unicode): if not encoding: encoding = 'utf-8' xml_input = ...
Top answer
1 of 16
406

xmltodict (full disclosure: I wrote it) does exactly that:

import xmltodict

xmltodict.parse("""<?xml version="1.0" ?>
<person>
  <name>john</name>
   <age>20</age>
</person>""")
# {'person': {'age': '20', 'name': 'john'}}
2 of 16
87

This is a great module that someone created. I've used it several times. http://code.activestate.com/recipes/410469-xml-as-dictionary/

Here is the code from the website just in case the link goes bad.

from xml.etree import cElementTree as ElementTree

class XmlListConfig(list):
    def __init__(self, aList):
        for element in aList:
            if element:
                # treat like dict
                if len(element) == 1 or element[0].tag != element[1].tag:
                    self.append(XmlDictConfig(element))
                # treat like list
                elif element[0].tag == element[1].tag:
                    self.append(XmlListConfig(element))
            elif element.text:
                text = element.text.strip()
                if text:
                    self.append(text)


class XmlDictConfig(dict):
    '''
    Example usage:

    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)

    Or, if you want to use an XML string:

    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)

    And then use xmldict for what it is... a dict.
    '''
    def __init__(self, parent_element):
        if parent_element.items():
            self.update(dict(parent_element.items()))
        for element in parent_element:
            if element:
                # treat like dict - we assume that if the first two tags
                # in a series are different, then they are all different.
                if len(element) == 1 or element[0].tag != element[1].tag:
                    aDict = XmlDictConfig(element)
                # treat like list - we assume that if the first two tags
                # in a series are the same, then the rest are the same.
                else:
                    # here, we put the list in dictionary; the key is the
                    # tag name the list elements all share in common, and
                    # the value is the list itself 
                    aDict = {element[0].tag: XmlListConfig(element)}
                # if the tag has attributes, add those to the dict
                if element.items():
                    aDict.update(dict(element.items()))
                self.update({element.tag: aDict})
            # this assumes that if you've got an attribute in a tag,
            # you won't be having any text. This may or may not be a 
            # good idea -- time will tell. It works for the way we are
            # currently doing XML configuration files...
            elif element.items():
                self.update({element.tag: dict(element.items())})
            # finally, if there are no child tags and no attributes, extract
            # the text
            else:
                self.update({element.tag: element.text})

Example usage:

tree = ElementTree.parse('your_file.xml')
root = tree.getroot()
xmldict = XmlDictConfig(root)

//Or, if you want to use an XML string:

root = ElementTree.XML(xml_string)
xmldict = XmlDictConfig(root)
🌐
Pythonrepo
pythonrepo.com › repo › martinblech-xmltodict-python-working-with-html-and-xml
Python module that makes working with XML feel like you are working with JSON | PythonRepo
January 12, 2022 - >>> for (stack, value) in xmltodict.parse(xml2, generator=True, item_depth=3): ... print "\tValue: %r" % value ...