Convert XML to JSON in Python While Preserving Inline Text Order
XML can mix text and nested tags within a single paragraph. If your output needs to display that paragraph with markup, preserve the order of the strings and child elements during conversion.
Worked example
Convert a paragraph with nested emphasis
import json
import xml.etree.ElementTree as ET
source = "<p>Ship <strong>three</strong> cases today.</p>"
def encode(element):
parts = [element.text] if element.text is not None else []
for child in element:
parts.append(encode(child))
if child.tail is not None:
parts.append(child.tail)
return {"tag": element.tag, "parts": parts}
print(json.dumps(encode(ET.fromstring(source)), indent=2))Steps
- Save the example as mixed.py and run python3 mixed.py. ElementTree stores text before the first child as element.text and the text immediately after a child as that child's tail.
- Use an array of alternating text strings and nested element objects for the output. The example builds parts recursively and attaches each tail immediately after its child.
- Test a paragraph with no child and one with two inline tags. Check whether consumers can display the full sentence while preserving the emphasis order.
What to check
- The parts array should contain 'Ship ', the strong node, and ' cases today.' in that order. Stripping the spaces from each part can join words when the sentence is reconstructed.
- This mapping preserves inline text for the sample. XML comments, attributes, and namespace resolution need their own explicit rules when they matter.