# Convert XML to JSON: Attributes, Repeats and Namespaces

> Canonical: https://skillalmanac.com/learn/convert-xml-to-json-with-an-ai-agent | Updated: 2026-11-21 | Index status: not offered to search engines

Steps for converting XML to JSON with an AI agent, with rules for attributes, repeated tags and namespaces, and checks to run on the output.

## Facts

- 2026-11-21: ET.parse returns an ElementTree and ET.fromstring returns the root Element (https://docs.python.org/3/library/xml.etree.elementtree.html)
- 2026-11-21: findall returns direct children only, while iter walks all descendants (https://docs.python.org/3/library/xml.etree.elementtree.html)
- 2026-11-21: ElementTree expands prefixed tags to the {uri}localname form (https://docs.python.org/3/library/xml.etree.elementtree.html)
- 2026-11-21: RFC 8259 says object names SHOULD be unique and leaves duplicate-name behavior unpredictable (https://www.rfc-editor.org/rfc/rfc8259)
- 2026-11-21: RFC 8259 treats JSON objects as unordered and says software should not depend on member order (https://www.rfc-editor.org/rfc/rfc8259)
- 2026-11-21: In XML Namespaces, an expanded name is a namespace name plus a local name, and prefixes are placeholders (https://www.w3.org/TR/xml-names/)

Converting XML to JSON means mapping a tree onto JSON objects and arrays, and the hard cases are the three XML features JSON has no direct equivalent for: attributes, repeated sibling tags, and namespaces. An AI agent can write and run the converter, but you should fix the mapping rules in writing before it starts, because an agent left to decide will pick rules silently and differently from one file to the next.

## Steps

1. Collect samples. Gather at least two XML files: one with attributes, one with a tag that repeats under the same parent, and one with a namespace declaration.
2. Write the mapping rules first. Decide each of these before any code exists:
   - Attributes: place them under one fixed prefix such as `@id`, so they cannot collide with child element names.
   - Text in an element that also has attributes or children: store it under a fixed key such as `#text`.
   - Repeated tags: always emit an array for a tag that can repeat, even when a sample contains only one. Otherwise an array of one and a single value look different to readers.
   - Namespaces: decide whether keys keep the prefix (`dc:title`) or use the namespace URI.
3. Ask the agent to parse with `xml.etree.ElementTree`. Use `ET.parse(path)` for files, which returns an ElementTree you then call `getroot()` on, or `ET.fromstring(text)` for strings, which returns the root Element directly. Ask for `findall` when the code needs direct children only, and for `iter` only when it needs descendants at any depth. `findall` will not reach grandchildren, so a converter that uses it on the wrong level drops nodes without an error.

4. Ask for explicit namespace handling. ElementTree expands a prefixed tag to `{uri}localname`. Have the agent pass a prefix map instead of hard-coding prefixes, for example `ns = {'dc': 'http://purl.org/dc/elements/1.1/'}` and then `root.findall('dc:title', ns)`. A file that binds the same URI to a different prefix then still works.

5. Run the converter on every sample, plus one file where a tag appears only once.

6. Read the output against the rules from step 2. Each repeating tag should be a list in every file, attribute keys should match the `@` rule, and no element should be missing because a lookup returned `None`.

## Check that it worked

Count elements per tag in each XML file with `root.iter()`, and count the matching keys in the JSON output. Equal counts for every tag mean no node was dropped. Then load the output with a JSON parser; a parse error means the agent emitted invalid JSON, which usually comes from unescaped text.

## Pitfalls

- Key collisions after prefix stripping. Two tags such as `a:id` and `b:id` both become `id`, and one value overwrites the other. Keep the prefix or the URI in the key whenever two namespaces share a local name. RFC 8259 says object names SHOULD be unique and leaves behavior with duplicates unpredictable, so make the converter raise an error on a collision instead of letting the last value win.
- Attributes and children sharing a name. An attribute `name` and a child `<name>` map to the same key unless attributes carry a prefix. Apply the `@` rule to every attribute.
- Prefix changes between files. One file binds `xmlns:d` where another binds `xmlns:dc`, and a hard-coded lookup then returns nothing. Bind prefixes by URI, as in step 4, because prefixes are placeholders in XML Namespaces.
- Lost mixed text. `element.text` holds only the text before the first child, and `element.tail` holds the text after an element's end tag. Use `"".join(element.itertext())` where you need all text, or the converter will silently keep only part of a mixed-content element.
- Untrusted input. The ElementTree documentation links to a security section for parsing untrusted data and does not summarize it. Read that section before pointing the converter at XML from outside your system.

## When to use a skill instead

A one-off conversion is fine as ad-hoc prompting. The case for a reusable skill appears when you convert batches on a schedule and need the same mapping rules applied each time. The related skill [json-schema-from-sample](/skills/skill-almanac/json-schema-from-sample) works on the other side of the pipeline: it takes example JSON files and drafts a JSON Schema, marking a property as required only when every sample contains it. Running it on converted output shows whether a tag that repeated in one file became an array everywhere it should. It does not parse XML, so the agent still writes the parser for step 3.

## FAQ

### Are XML and JSON the same?

No. JSON has objects, arrays and member names, and it has no concept of attributes, namespaces or mixed text, so the rules in step 2 decide how those XML features become keys and values.

### Does key order in the JSON output matter?

For the format, no. RFC 8259 treats objects as unordered collections and says software should not depend on member order. Order is meaningful only inside arrays, so a repeated tag converted to an array keeps its document order.

### What happens when one object has the same key twice?

The RFC leaves it undefined, and parsers differ: some keep the last value, others reject the object. Have the converter detect collisions and fail loudly, then fix the key naming rule.

## Related skills

- [json-schema-from-sample](https://skillalmanac.com/skills/skill-almanac/json-schema-from-sample.md): Platform Score 42/100 (provisional)

## Related guides

- [Convert JSON to CSV: Nested Data, Nulls and Checks](https://skillalmanac.com/learn/convert-json-to-csv-with-an-ai-agent.md)
- [Create a Sitemap XML: Generate, Validate and Submit](https://skillalmanac.com/learn/create-a-sitemap-xml-with-an-ai-agent.md)
- [How to Use an AI Agent on a First Task You Can Check](https://skillalmanac.com/learn/how-to-use-an-ai-agent.md)
- [Check a Resume for ATS Problems With an AI Agent](https://skillalmanac.com/learn/check-a-resume-for-ats-with-an-ai-agent.md)

## Sources

- https://docs.python.org/3/library/xml.etree.elementtree.html
- https://www.rfc-editor.org/rfc/rfc8259
- https://www.w3.org/TR/xml-names/

Platform Scores report our assessment under a published method. They are not a safety guarantee.
