Understanding XML With Python Data Structures

Understanding XML With Python Data Structures

Your Python script reads an XML file without an error, yet half the information disappears during conversion. A repeated tag becomes one value. A product code loses its leading zeros. A sentence loses words around a child element. These problems often begin with a reasonable assumption: XML looks like a dictionary. Understanding where that comparison works, and where it breaks, makes XML much easier to handle.

Three Ideas to Keep Close

  1. Use dictionaries for named fields and lists for repeated records.
  2. Keep XML structure when order, attributes, or mixed text matter.
  3. Check converted output against both your source and its destination.

Read XML as a Tree Before Choosing a Structure

XML describes a hierarchy of elements. Each element has a name, may have attributes, and may contain text or child elements. Python can represent those relationships, but no single dictionary layout fits every document.

Start with a small inventory file:

<inventory>
  <item code="0017">
    <name>Desk lamp</name>
    <quantity>4</quantity>
  </item>
  <item code="0023">
    <name>Reading chair</name>
    <quantity>2</quantity>
  </item>
</inventory>

The inventory is the root element. It contains two item elements. Each item has a code attribute and two child elements. The repeated items suggest a Python list. Each item’s named fields suggest a dictionary.

That gives you a useful working representation:

items = [
    {"code": "0017", "name": "Desk lamp", "quantity": 4},
    {"code": "0023", "name": "Reading chair", "quantity": 2},
]

Notice the choices already made. The code stays a string because its leading zeros carry meaning. The quantity becomes an integer because the script will count stock. XML text does not automatically tell Python which conversion your application needs.

Turn Elements Into Useful Python Records

Python’s standard library includes xml.etree.ElementTree. It lets you parse a document, select elements, read attributes, and extract text. Its element API documents these operations and the distinction between an element and a complete document tree.

For the inventory above, save the XML as inventory.xml and use an explicit mapping:

import xml.etree.ElementTree as ET

tree = ET.parse("inventory.xml")
root = tree.getroot()

if root.tag != "inventory":
    raise ValueError("Expected an inventory document")

items = []

for element in root.findall("item"):
    code = element.get("code")
    name = element.findtext("name")
    quantity_text = element.findtext("quantity")

    if code is None or not code.strip():
        raise ValueError("An item has no code")
    if name is None or not name.strip():
        raise ValueError(f"Item {code} has no name")
    if quantity_text is None:
        raise ValueError(f"Item {code} has no quantity")

    quantity = int(quantity_text)
    if quantity < 0:
        raise ValueError(f"Item {code} has a negative quantity")

    items.append({
        "code": code,
        "name": name.strip(),
        "quantity": quantity,
    })

This code defines a contract. Every item needs a code, a usable name, and a whole-number quantity. Invalid quantity text raises an error instead of quietly becoming zero.

That behavior helps in automation. A scheduled import should make missing data visible. Inventing defaults can produce a successful-looking run with incorrect stock figures.

The mapping also has a clear boundary. It extracts selected inventory fields. It does not preserve every possible element or attribute that a future file might contain. If the supplier adds a warehouse field, update the mapping deliberately.

Choose Dictionaries, Lists, and Trees by Meaning

A dictionary is convenient when each key represents one field. A list suits repeated values and preserves their sequence. An element tree suits work that depends on XML relationships.

How Python Structures Handle XML Features

XML Feature Useful Python Choice Main Check
Named record fields Dictionary Define required and optional keys.
Repeated elements List of records Retain every occurrence and its order.
Attributes and child elements Separate dictionary fields or an element tree Avoid collisions between attribute and element names.
Text surrounding child elements Element tree Preserve text placement when formatting matters.

A frequent mistake is building a dictionary with each child tag as a key. If three children share that tag, later assignments overwrite earlier values. A converter may also represent one occurrence as an object and several occurrences as a list. Your consuming code then receives different shapes from similar files.

Choose a stable rule. If a field can repeat, represent it as a list even when today’s sample contains only one value.

Keep Text, Namespaces, and Empty Values Straight

Documents containing prose need extra care. Consider this fragment:

<message>Read the <strong>updated</strong> instructions.</message>

With ElementTree, the message element’s .text contains the text before the strong element. The strong element’s .tail contains the text after it. Reading only the parent’s .text loses part of the sentence.

message = ET.fromstring(
    "<message>Read the <strong>updated</strong> instructions.</message>"
)

plain_text = "".join(message.itertext())
print(plain_text)

This produces the complete sentence as plain text. It removes the distinction carried by the strong element. Keep the tree if you need to write that formatting back later.

Namespaces introduce another naming detail. An element written with a prefix may appear in ElementTree as {namespace-uri}name. Search with a namespace mapping rather than removing prefixes through string replacement:

namespaces = {"s": "urn:example:stock"}
records = root.findall("s:item", namespaces)

Missing and empty values also deserve separate decisions. An absent quantity might mean the supplier omitted it. An empty quantity might mean the field exists but has no value. Converting both to zero erases that distinction. Decide what each state means before exporting to JSON, CSV, or a database.

Use Browser Conversion for Small Inspection Tasks

A free browser-based service fits naturally when you have a small, non-sensitive sample and want to inspect a conversion without writing a script first. An XML file converter can be a starting point for that manual check. Confirm its available input and output options before relying on a particular conversion.

Use the result to examine mapping decisions. Did repeated elements become arrays? Where did attributes go? Did a code remain a string? Those questions connect browser inspection with the same Python structures your application will use.

A manual conversion can also help you understand an unfamiliar supplier export. Once the mapping is settled, a Python script is easier to repeat across daily files. Keep a small approved sample and its expected output as reference material.

Being browser-based does not establish where processing happens. Before submitting private information, check the service’s current processing, retention, and deletion information. If those details are unclear, use synthetic records or process the file locally.

Check Compatibility Before Flattening a Document

Changing a filename extension does not convert its contents. Actual conversion requires a mapping between the source format and the destination’s rules.

JSON supports objects, arrays, strings, numbers, booleans, and null. It has no built-in distinction between an XML attribute and a child element. CSV organizes data into rows and columns, so repeated child records require an agreed layout.

Before choosing that layout, check the receiving application:

  • Confirm its required field names and accepted data types.
  • Check how it handles repeated records and missing values.
  • Verify its character encoding and date expectations.
  • Test whether identifiers retain leading zeros.
  • Decide how attributes, namespaces, and record order will be represented.

For data science work, flattening inventory items into rows may be useful. For a web application exchanging document content, preserving the XML tree may be safer. Let the destination’s needs guide the representation.

Validate Syntax and Then Check the Data

A parser accepting your file answers one question: can it read the XML structure? It does not prove that every record meets your business rules.

The XML specification distinguishes well-formed documents from valid documents. Well-formedness covers XML syntax requirements. Formal validation checks declared constraints. Your application may need further checks, including unique product codes or acceptable stock quantities.

ElementTree parsing alone does not validate against an XML Schema. If your recipient requires schema validation, include a validator that supports that schema language.

Use this sequence when checking a conversion:

  1. Preserve the original file and work from a copy.
  2. Parse the source and confirm its expected root and record count.
  3. Convert using explicit rules for types, repetition, and missing values.
  4. Read the output with a parser for its destination format.
  5. Compare record counts, identifiers, totals, and representative text values.
  6. Test the result in the application that will actually consume it.

For our inventory, the record count should remain two and the total quantity should remain six. Check both codes directly. A matching total would not reveal that 0017 had become 17.

Preserve Originals and Write Output Deliberately

A useful conversion does not necessarily preserve a document exactly. Parsing and writing XML can change whitespace, namespace prefixes, or empty-element formatting. Default ElementTree parsing also skips comments and processing instructions.

Keep the original bytes when you need an archive, an audit record, or a signed document. Saving the original beside a derived JSON file gives you a reliable source for later corrections.

When creating new XML, let the serializer escape special characters. Hand-built strings can break when a name contains an ampersand or a less-than character.

output_root = ET.Element("inventory")

for record in items:
    item = ET.SubElement(
        output_root, "item", {"code": record["code"]}
    )
    ET.SubElement(item, "name").text = record["name"]
    ET.SubElement(item, "quantity").text = str(record["quantity"])

ET.ElementTree(output_root).write(
    "inventory-output.xml",
    encoding="utf-8",
    xml_declaration=True,
)

For externally supplied files, consider parser security and resource limits as part of the workflow. Local processing protects against unnecessary uploads, but it does not make arbitrary XML safe to parse. Large files may also need incremental processing instead of loading the entire tree into memory.

Give Every Converted Value a Clear Home

XML becomes easier to work with when each piece of information has a deliberate place. Repeated records belong in lists. Named fields fit dictionaries. Document relationships may need an element tree.

Begin with a small sample. Define what must survive conversion. Check the result where it will be used. That habit turns XML handling into a manageable Python task, whether you are preparing a dataset, building a web import, or scheduling tomorrow’s inventory update.

Leave a Reply

Your e-mail address will not be published.