Converts XML into JSON/Python dicts/arrays and vice-versa using multiple conventions
BadgerFish convention uses @ prefix for XML attributes and $ for text content, creating a clean and widely-supported JSON representation of XML structures.
Creates a BadgerFish converter with @ prefix for attributes and $ for text content.
class BadgerFish(XMLData):
def __init__(self, **kwargs):
"""
Initialize BadgerFish converter.
Parameters:
- **kwargs: Additional XMLData parameters (xml_fromstring, xml_tostring,
element, dict_type, list_type, simple_text, invalid_tags)
"""Converts Python dictionaries and lists to XML elements using BadgerFish convention.
def etree(self, data, root=None):
"""
Convert data structure into a list of etree.Element.
Parameters:
- data: dict or list, data structure to convert
- root: Element, optional root element to append to
Returns:
List of etree.Element objects or modified root element
"""Usage Example:
from xmljson import badgerfish as bf
from xml.etree.ElementTree import Element, tostring
# Convert dictionary to XML
data = {'p': {'@id': 'main', '$': 'Hello', 'b': 'bold'}}
elements = bf.etree(data)
print(tostring(elements[0]).decode())
# Output: <p id="main">Hello<b>bold</b></p>
# Convert with existing root element
root = Element('root')
result = bf.etree({'p': {'@id': 'main'}}, root=root)
print(tostring(result).decode())
# Output: <root><p id="main"/></root>Converts XML elements to Python dictionaries using BadgerFish convention.
def data(self, root):
"""
Convert etree.Element into a dictionary.
Parameters:
- root: Element, XML element to convert
Returns:
dict: Dictionary representation using BadgerFish convention
"""Usage Example:
from xmljson import badgerfish as bf
from xml.etree.ElementTree import fromstring
import json
# Convert XML to dictionary
xml_string = '<p id="main">Hello<b>bold</b></p>'
xml_element = fromstring(xml_string)
data = bf.data(xml_element)
print(json.dumps(data))
# Output: {"p": {"@id": "main", "$": "Hello", "b": {"$": "bold"}}}badgerfish: BadgerFishA pre-configured BadgerFish instance available at module level for immediate use.
id="main" becomes "@id": "main")<p>text</p> becomes {"p": {"$": "text"}})true/false (lowercase) in XML, True/False in Pythoninvalid_tags='drop' parameter