XML Namespaces and JSON Conversion
Understand how XML namespaces work and how they are represented in JSON. Covers namespace prefixes, default namespaces, and strategies for preserving namespace information.
Detailed Explanation
XML namespaces prevent element name collisions when combining documents from different vocabularies. They have no direct JSON equivalent, making them one of the trickiest aspects of XML-JSON conversion.
XML with namespaces:
<order xmlns="http://example.com/orders"
xmlns:pay="http://example.com/payments">
<id>ORD-001</id>
<total>99.99</total>
<pay:method>credit_card</pay:method>
<pay:status>completed</pay:status>
</order>
JSON representation strategies:
Strategy 1: Prefix preservation
{
"order": {
"@xmlns": "http://example.com/orders",
"@xmlns:pay": "http://example.com/payments",
"id": "ORD-001",
"total": "99.99",
"pay:method": "credit_card",
"pay:status": "completed"
}
}
Strategy 2: Namespace stripping (lossy but simpler)
{
"order": {
"id": "ORD-001",
"total": "99.99",
"method": "credit_card",
"status": "completed"
}
}
Strategy 3: Clark notation (unambiguous)
{
"{http://example.com/orders}order": {
"{http://example.com/orders}id": "ORD-001",
"{http://example.com/orders}total": "99.99",
"{http://example.com/payments}method": "credit_card",
"{http://example.com/payments}status": "completed"
}
}
How namespaces work in XML:
xmlns="..."declares a default namespace. All unqualified elements belong to this namespace.xmlns:prefix="..."declares a prefixed namespace. Elements use the prefix (pay:method) to indicate their namespace.- Namespaces are inherited. Child elements inherit the default namespace from their parent unless overridden.
Practical advice for conversion:
- If you control both ends (JSON producer and XML consumer), agree on a convention and document it.
- For SOAP/WSDL interop, preserve namespace prefixes because the receiving service validates them.
- For data extraction only (no round-trip needed), strip namespaces for cleaner JSON.
- Watch out for namespace-qualified attributes, which are less common but do occur in schemas like
xsi:typeandxml:lang.
Use Case
Parsing SOAP API responses that use multiple XML namespaces for different schema components (envelope, body, custom types) and converting them into namespace-aware JSON for a TypeScript middleware layer.