Package: xmljson-adv
This library is not actively maintained. Alternatives arexmltodictanduntangle.
Use only if you need to parse using specific XML to JSONconventions.xmljson converts XML into Python dictionary structures (trees, like in JSON) and vice-versa.AboutXML can be converted to a data structure (such as JSON) and back. For example:<employees>
    <person>
        <name value="Alice"/>
    </person>
    <person>
        <name value="Bob"/>
    </person>
</employees>can be converted into this data structure (which also a valid JSON object):{
    "employees": [{
        "person": {
            "name": {
                "@value": "Alice"
            }
        }
    }, {
        "person": {
            "name": {
                "@value": "Bob"
            }
        }
    }]
}This uses theBadgerFishconvention that prefixes attributes with@.
The conventions supported by this library are:Abdera: Use"attributes"for attributes,"children"for nodesBadgerFish: Use"$"for text content,@to prefix attributesCobra: Use"attributes"for sorted attributes (even when empty),"children"for nodes, values are stringsGData: Use"$t"for text content, attributes added as-isParker: Use tail nodes for text content, ignore attributesYahooUse"content"for text content, attributes added as-isConvert data to XMLTo convert from a data structure to XML using the BadgerFish convention:>>> from xmljson import badgerfish as bf
>>> bf.etree({'p': {'@id': 'main', '$': 'Hello', 'b': 'bold'}})This returns anarrayofetree.Elementstructures. In this case, the
result is identical to:>>> from xml.etree.ElementTree import fromstring
>>> [fromstring('<p id="main">Hello<b>bold</b></p>')]The result can be inserted into any existing rootetree.Element:>>> from xml.etree.ElementTree import Element, tostring
>>> result = bf.etree({'p': {'@id': 'main'}}, root=Element('root'))
>>> tostring(result)
'<root><p id="main"/></root>'This includeslxml.htmlas well:>>> from lxml.html import Element, tostring
>>> result = bf.etree({'p': {'@id': 'main'}}, root=Element('html'))
>>> tostring(result, doctype='<!DOCTYPE html>')
'<!DOCTYPE html>\n<html><p id="main"></p></html>'For ease of use, strings are treated as node text. For example, both the
following are the same:>>> bf.etree({'p': {'$': 'paragraph text'}})
>>> bf.etree({'p': 'paragraph text'})By default, non-string values are converted to strings using Python’sstr,
except for booleans – which are converted intotrueandfalse(lower
case). Override this behaviour usingxml_fromstring:>>> tostring(bf.etree({'x': 1.23, 'y': True}, root=Element('root')))
'<root><y>true</y><x>1.23</x></root>'
>>> from xmljson import BadgerFish              # import the class
>>> bf_str = BadgerFish(xml_tostring=str)       # convert using str()
>>> tostring(bf_str.etree({'x': 1.23, 'y': True}, root=Element('root')))
'<root><y>True</y><x>1.23</x></root>'If the data contains invalid XML keys, these can be dropped viainvalid_tags='drop'in the constructor:>>> bf_drop = BadgerFish(invalid_tags='drop')
>>> data = bf_drop.etree({'$': '1', 'x': '1'}, root=Element('root'))    # Drops invalid <$> tag
>>> tostring(data)
'<root>1<x>1</x></root>'Convert XML to dataTo convert from XML to a data structure using the BadgerFish convention:>>> bf.data(fromstring('<p id="main">Hello<b>bold</b></p>'))
{"p": {"$": "Hello", "@id": "main", "b": {"$": "bold"}}}To convert this to JSON, use:>>> from json import dumps
>>> dumps(bf.data(fromstring('<p id="main">Hello<b>bold</b></p>')))
'{"p": {"b": {"$": "bold"}, "@id": "main", "$": "Hello"}}'To preserve the order of attributes and children, specify thedict_typeasOrderedDict(or any other dictionary-like type) in the constructor:>>> from collections import OrderedDict
>>> from xmljson import BadgerFish              # import the class
>>> bf = BadgerFish(dict_type=OrderedDict)      # pick dict classBy default, values are parsed into boolean, int or float where possible (except
in the Yahoo method). Override this behaviour usingxml_fromstring:>>> dumps(bf.data(fromstring('<x>1</x>')))
'{"x": {"$": 1}}'
>>> bf_str = BadgerFish(xml_fromstring=False)   # Keep XML values as strings
>>> dumps(bf_str.data(fromstring('<x>1</x>')))
'{"x": {"$": "1"}}'
>>> bf_str = BadgerFish(xml_fromstring=repr)    # Custom string parser
'{"x": {"$": "\'1\'"}}'xml_fromstringcan be any custom function that takes a string and returns a
value. In the example below, only the integer1is converted to an integer.
Everything else is retained as a float:>>> def convert_only_int(val):
...     return int(val) if val.isdigit() else val
>>> bf_int = BadgerFish(xml_fromstring=convert_only_int)
>>> dumps(bf_int.data(fromstring('<p><x>1</x><y>2.5</y><z>NaN</z></p>')))
'{"p": {"x": {"$": 1}, "y": {"$": "2.5"}, "z": {"$": "NaN"}}}'ConventionsTo use a different conversion method, replaceBadgerFishwith one of the
other classes. Currently, these are supported:>>> from xmljson import abdera          # == xmljson.Abdera()
>>> from xmljson import badgerfish      # == xmljson.BadgerFish()
>>> from xmljson import cobra           # == xmljson.Cobra()
>>> from xmljson import gdata           # == xmljson.GData()
>>> from xmljson import parker          # == xmljson.Parker()
>>> from xmljson import yahoo           # == xmljson.Yahoo()OptionsConventions may support additional options.TheParkerconvention absorbs the root element by default.parker.data(preserve_root=True)preserves the root instance:>>> from xmljson import parker, Parker
>>> from xml.etree.ElementTree import fromstring
>>> from json import dumps
>>> dumps(parker.data(fromstring('<x><a>1</a><b>2</b></x>')))
'{"a": 1, "b": 2}'
>>> dumps(parker.data(fromstring('<x><a>1</a><b>2</b></x>'), preserve_root=True))
'{"x": {"a": 1, "b": 2}}'InstallationThis is a pure-Python package built for Python 2.7+ and Python 3.0+. To set up:pip install xmljsonSimple CLI utilityAfter installation, you can benefit from using this package as simple CLI utility. By now only XML to JSON conversion supported. Example:$ python -m xmljson -h
usage: xmljson [-h] [-o OUT_FILE]
            [-d {abdera,badgerfish,cobra,gdata,parker,xmldata,yahoo}]
            [in_file]

positional arguments:
in_file               defaults to stdin

optional arguments:
-h, --help            show this help message and exit
-o OUT_FILE, --out_file OUT_FILE
                        defaults to stdout
-d {abdera,badgerfish,...}, --dialect {...}
                        defaults to parker

$ python -m xmljson -d parker tests/mydata.xml
{
  "foo": "spam",
  "bar": 42
}This is a typical UNIX filter program: it reads file (orstdin), processes it in some way (convert XML to JSON in this case), then prints it tostdout(or file). Example with pipe:$ some-xml-producer | python -m xmljson | some-json-processorThere is alsopip’sconsole_scriptentry-point, you can call this utility asxml2json:$ xml2json -d abdera mydata.xmlRoadmapTest cases for UnicodeSupport for namespaces and namespace prefixesSupport XML commentsHistory0.2.0 (21 Nov 2018)xmljsoncommand line script converts from XML to JSON (@tribals)invalid_tags='drop'in the constructor drops invalid XML tags in.etree()(@Zurga)Bugfix: Parker converts{‘x’: null}to<x></x>instead of<x>None</x>(@jorndoe #29)0.1.9 (1 Aug 2017)Bugfix and test cases for multiple nested children inAbderaconventionThanks to @mukultaneja0.1.8 (9 May 2017)AddAbderaandCobraconventionsAddParker.data(preserve_root=True)option to preserve root element in
Parker convention.Thanks to @dagwieers0.1.6 (18 Feb 2016)Addxml_fromstring=andxml_tostring=parameters to constructor to
customise string conversion from and to XML.0.1.5 (23 Sep 2015)Add theYahooXML to JSON conversion method.0.1.4 (20 Sep 2015)FixGData.etree()conversion of attributes. (They were ignored. They
should be added as-is.)0.1.3 (20 Sep 2015)Simplify{'p':{'$':'text'}}to{'p': 'text'}in BadgerFish and GData
conventions.Add test cases for.etree()– mainly from theMDN JXON article.dict_type/list_typedo not need to inherit fromdict/list0.1.2 (18 Sep 2015)Always use thedict_typeclass to create dictionaries (which defaults toOrderedDictto preserve order of keys)Update documentation, test casesRemove support for Python 2.6 (since we needcollections.Counter)Make theTravis CI buildpass0.1.1 (18 Sep 2015)Converttrue,falseand numeric values from strings to Python typesxmljson.parker.data()is compliant with Parker convention (bugs resolved)0.1.0 (15 Sep 2015)Two-way conversions via BadgerFish, GData and Parker conventions.First release on PyPI.