XML 转 JSON 转换器
将 XML 转换为 JSON 格式
XML 输入
JSON 输出
什么是 XML 转 JSON?
XML 转 JSON 是将数据从可扩展标记语言(XML)转换为 JavaScript 对象表示法(JSON)的过程。两种格式都能表示结构化的层级数据,但使用不同的语法和数据模型。XML 使用开闭标签和可选属性,而 JSON 使用键值对、数组和基本类型。将 XML 转换为 JSON,可以在 JSON 作为原生格式的环境中使用 XML 数据,例如 JavaScript 运行时、REST API 和 NoSQL 数据库。
转换并非总是一一对应的。XML 有一些在 JSON 中没有直接等价物的构造:属性、混合内容(文本与子元素交叉出现)、处理指令、注释、CDATA 节和命名空间声明。不同的转换库对这些构造的处理方式各异,这也是存在多种转换约定的原因。最常见的方案是对属性名添加 @ 前缀,当同一元素同时存在属性和文本内容时,将文本内容放入 #text 字段。
XML 转 JSON 是从 SOAP 迁移到 REST、使用旧式企业 API、或处理政府和金融数据(这些数据通常以 XML 格式提供)时的常见步骤。团队无需同时重写生产者和消费者,而是在边界层将 XML 负载转换为 JSON,再向下游传递。AWS API Gateway、Apache Camel 和 MuleSoft 均原生支持此模式。
<bookstore>
<book category="fiction">
<title lang="en">The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
<price>10.99</price>
</book>
<book category="non-fiction">
<title lang="en">Sapiens</title>
<author>Yuval Noah Harari</author>
<year>2011</year>
<price>14.99</price>
</book>
</bookstore>{
"bookstore": {
"book": [
{
"@category": "fiction",
"title": {
"@lang": "en",
"#text": "The Great Gatsby"
},
"author": "F. Scott Fitzgerald",
"year": "1925",
"price": "10.99"
},
{
"@category": "non-fiction",
"title": {
"@lang": "en",
"#text": "Sapiens"
},
"author": "Yuval Noah Harari",
"year": "2011",
"price": "14.99"
}
]
}
}为什么使用在线 XML 转 JSON 转换器?
编写一次性转换脚本需要时间,尤其是当 XML 包含属性、命名空间或需要转换为 JSON 数组的重复元素时。基于浏览器的转换器能在数秒内输出 JSON 结果,让您快速检查结构后继续工作。
XML 转 JSON 使用场景
XML 转 JSON 映射参考
XML 和 JSON 的数据模型不同。下表展示了在最常见约定下(属性使用 @,与属性共存的文本内容使用 #text),每种 XML 构造如何映射为对应的 JSON。混合内容和注释等构造没有标准的 JSON 表示形式。
| XML 构造 | XML 示例 | JSON 等价形式 |
|---|---|---|
| Element | <name>text</name> | "name": "text" |
| Nested elements | <a><b>1</b></a> | "a": { "b": "1" } |
| Attributes | <el attr="v"/> | "el": { "@attr": "v" } |
| Text + attributes | <el a="1">text</el> | "el": { "@a": "1", "#text": "text" } |
| Repeated elements | <r><i>1</i><i>2</i></r> | "r": { "i": ["1", "2"] } |
| Mixed content | <p>A <b>B</b> C</p> | Varies by convention |
| CDATA | <![CDATA[raw]]> | "#cdata": "raw" or flattened |
| Namespaces | xmlns:prefix="uri" | Prefix preserved or stripped |
| Empty element | <el/> | "el": null or "" |
| Comments | <!-- note --> | Discarded (no JSON equivalent) |
XML 转 JSON 约定对比
目前没有统一的标准规定 XML 如何映射为 JSON。三种约定被广泛使用,各自在属性处理、数组检测和文本保留方面有不同的权衡。
代码示例
以下是在 JavaScript、Python、Go 和命令行中将 XML 转换为 JSON 的可运行示例。每个示例均处理了嵌套元素和重复同级标签。
// Using the DOMParser API to walk XML and build a JSON object
function xmlToJson(xml) {
const parser = new DOMParser()
const doc = parser.parseFromString(xml, 'application/xml')
function nodeToObj(node) {
const obj = {}
// Handle attributes
if (node.attributes) {
for (const attr of node.attributes) {
obj['@' + attr.name] = attr.value
}
}
// Handle child nodes
for (const child of node.childNodes) {
if (child.nodeType === 3) { // text
const text = child.textContent.trim()
if (text) obj['#text'] = text
} else if (child.nodeType === 1) { // element
const key = child.nodeName
const val = nodeToObj(child)
if (obj[key]) {
if (!Array.isArray(obj[key])) obj[key] = [obj[key]]
obj[key].push(val)
} else {
obj[key] = val
}
}
}
// Simplify text-only nodes
const keys = Object.keys(obj)
if (keys.length === 1 && keys[0] === '#text') return obj['#text']
return obj
}
return nodeToObj(doc.documentElement)
}
const xml = '<user><name>Alice</name><role>admin</role></user>'
console.log(JSON.stringify(xmlToJson(xml), null, 2))
// → { "name": "Alice", "role": "admin" }import xmltodict
import json
xml = """
<user>
<name>Alice</name>
<roles>
<role>admin</role>
<role>editor</role>
</roles>
</user>
"""
# xmltodict converts XML to an OrderedDict
result = xmltodict.parse(xml)
print(json.dumps(result, indent=2))
# → {
# → "user": {
# → "name": "Alice",
# → "roles": { "role": ["admin", "editor"] }
# → }
# → }
# With the standard library (xml.etree.ElementTree)
import xml.etree.ElementTree as ET
def etree_to_dict(elem):
d = {}
if elem.attrib:
d.update({f"@{k}": v for k, v in elem.attrib.items()})
for child in elem:
child_data = etree_to_dict(child)
if child.tag in d:
if not isinstance(d[child.tag], list):
d[child.tag] = [d[child.tag]]
d[child.tag].append(child_data)
else:
d[child.tag] = child_data
if elem.text and elem.text.strip():
if d:
d["#text"] = elem.text.strip()
else:
return elem.text.strip()
return d
root = ET.fromstring(xml)
print(json.dumps(etree_to_dict(root), indent=2))package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"strings"
)
// For simple, known schemas — define a struct
type User struct {
XMLName xml.Name `xml:"user"`
Name string `xml:"name"`
Roles []string `xml:"roles>role"`
}
func main() {
data := `<user><name>Alice</name><roles><role>admin</role><role>editor</role></roles></user>`
var user User
xml.NewDecoder(strings.NewReader(data)).Decode(&user)
out, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(out))
// → { "Name": "Alice", "Roles": ["admin", "editor"] }
}# Using xq (part of yq, a jq wrapper for XML)
# Install: pip install yq OR brew install yq
echo '<user><name>Alice</name></user>' | xq .
# → { "user": { "name": "Alice" } }
# Using xmlstarlet + jq
xmlstarlet sel -t -v '//name' input.xml | jq -R '{ name: . }'
# Node.js one-liner with xml2js
echo '<a><b>1</b></a>' | node -e "
const {parseString} = require('xml2js');
let d=''; process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>parseString(d,(e,r)=>console.log(JSON.stringify(r,null,2))))
"