Convert XML Attributes to JSON Schema Properties
Understand how XML attributes are mapped to JSON Schema properties with configurable prefixes (@attr or _attr) and automatic type detection.
Detailed Explanation
Handling XML Attributes in JSON Schema
XML attributes carry metadata about elements, and they need a distinct representation in JSON Schema since JSON has no attribute concept. The converter uses a configurable prefix to distinguish attribute-derived properties from child element properties.
Example XML
<book isbn="978-0-13-468599-1" pages="832" available="true">
<title>The C Programming Language</title>
<author>Kernighan & Ritchie</author>
<year>1988</year>
</book>
Generated Schema with @ prefix
{
"type": "object",
"properties": {
"book": {
"type": "object",
"properties": {
"@isbn": { "type": "string" },
"@pages": { "type": "integer" },
"@available": { "type": "boolean" },
"title": { "type": "string" },
"author": { "type": "string" },
"year": { "type": "integer" }
}
}
}
}
@ vs _ Prefix
The @ prefix is the more common convention in XML-to-JSON mappings (used by libraries like xml2js and fast-xml-parser). However, some systems or databases do not allow @ in property names. In those cases, switch to the _ prefix, which produces _isbn, _pages, and _available instead.
Attribute Type Inference
Attribute values are type-inferred the same way as text content. In the example above, 978-0-13-468599-1 contains hyphens so it remains a string, 832 is detected as an integer, and true becomes a boolean.
Required Field Detection
When required detection is enabled, attributes that appear on every occurrence of an element are marked as required in the schema. This is especially useful when analyzing multiple instances of the same element type in your sample data.
Use Case
When working with XML formats that heavily use attributes, such as HTML/SVG elements, Android XML layouts, or XBRL financial reports. Understanding how attributes translate to schema properties helps when building JSON validation for converted XML data.