Converts XML into JSON/Python dicts/arrays and vice-versa using multiple conventions
GData convention uses $t for text content and attributes added as-is, following the format used by Google's GData APIs for XML-JSON conversion.
Creates a GData converter using $t for text content with attributes as direct properties.
class GData(XMLData):
def __init__(self, **kwargs):
"""
Initialize GData 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 GData 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
"""Converts XML elements to Python dictionaries using GData convention.
def data(self, root):
"""
Convert etree.Element into a dictionary.
Parameters:
- root: Element, XML element to convert
Returns:
dict: Dictionary representation using GData convention
"""Usage Examples:
from xmljson import gdata
from xml.etree.ElementTree import fromstring, tostring, Element
import json
# XML to data conversion
xml_string = '<entry><title type="text">Sample Title</title><content>Hello World</content></entry>'
xml_element = fromstring(xml_string)
data = gdata.data(xml_element)
print(json.dumps(data))
# Output: {"entry": {"title": {"type": "text", "$t": "Sample Title"}, "content": {"$t": "Hello World"}}}
# Data to XML conversion
data = {
'entry': {
'title': {'type': 'text', '$t': 'Sample Title'},
'content': {'$t': 'Hello World'}
}
}
elements = gdata.etree(data)
print(tostring(elements[0]).decode())
# Output: <entry><title type="text">Sample Title</title><content>Hello World</content></entry>gdata: GDataA pre-configured GData instance available at module level for immediate use.
<title>text</title> becomes {"title": {"$t": "text"}})The GData convention treats scalars differently based on context:
from xmljson import gdata
from xml.etree.ElementTree import fromstring
import json
# Element with text content
xml1 = '<item>text value</item>'
data1 = gdata.data(fromstring(xml1))
print(json.dumps(data1))
# Output: {"item": {"$t": "text value"}}
# Element with attribute and text
xml2 = '<item type="string">text value</item>'
data2 = gdata.data(fromstring(xml2))
print(json.dumps(data2))
# Output: {"item": {"type": "string", "$t": "text value"}}