本文目录导读:

我来介绍几种批量将JSON转换为XML的方法:
使用Python脚本
使用dicttoxml库(推荐)
import json
import os
import dicttoxml
from xml.dom.minidom import parseString
def json_to_xml(json_file, xml_file):
# 读取JSON文件
with open(json_file, 'r', encoding='utf-8') as f:
json_data = json.load(f)
# 转换为XML
xml_bytes = dicttoxml.dicttoxml(json_data)
xml_str = parseString(xml_bytes).toprettyxml()
# 写入XML文件
with open(xml_file, 'w', encoding='utf-8') as f:
f.write(xml_str)
def batch_convert(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.json'):
json_path = os.path.join(input_dir, filename)
xml_path = os.path.join(output_dir, filename.replace('.json', '.xml'))
print(f"转换: {filename}")
json_to_xml(json_path, xml_path)
# 使用示例
batch_convert('./json_files', './xml_files')
使用xmltodict库(更灵活的转换)
import json
import os
import xmltodict
from xml.dom.minidom import parseString
def json_to_xml_custom(json_file, xml_file):
with open(json_file, 'r', encoding='utf-8') as f:
json_data = json.load(f)
# 添加根节点
xml_data = {'root': json_data}
# 转换为XML
xml_str = xmltodict.unparse(xml_data, pretty=True)
with open(xml_file, 'w', encoding='utf-8') as f:
f.write(xml_str)
def batch_convert(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.json'):
json_path = os.path.join(input_dir, filename)
xml_path = os.path.join(output_dir, filename.replace('.json', '.xml'))
print(f"正在转换: {filename}")
try:
json_to_xml_custom(json_path, xml_path)
print(f"完成: {filename} -> {filename.replace('.json', '.xml')}")
except Exception as e:
print(f"错误 {filename}: {str(e)}")
# 使用示例
batch_convert('./json_input', './xml_output')
高级版本(支持多种选项)
import json
import os
import argparse
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.dom.minidom as minidom
class JSON2XMLConverter:
def __init__(self, root_name='root', pretty=True):
self.root_name = root_name
self.pretty = pretty
def dict_to_xml(self, data, parent=None):
if parent is None:
parent = Element(self.root_name)
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, (dict, list)):
child = SubElement(parent, str(key))
self.dict_to_xml(value, child)
else:
child = SubElement(parent, str(key))
child.text = str(value) if value is not None else ''
elif isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
child = SubElement(parent, 'item')
self.dict_to_xml(item, child)
else:
child = SubElement(parent, 'item')
child.text = str(item)
return parent
def convert_file(self, json_file, xml_file):
with open(json_file, 'r', encoding='utf-8') as f:
json_data = json.load(f)
root = self.dict_to_xml(json_data)
if self.pretty:
xml_str = minidom.parseString(tostring(root, encoding='unicode')).toprettyxml()
else:
xml_str = tostring(root, encoding='unicode')
with open(xml_file, 'w', encoding='utf-8') as f:
f.write(xml_str)
def batch_convert(self, input_dir, output_dir, recursive=False):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for root, dirs, files in os.walk(input_dir):
for file in files:
if file.endswith('.json'):
json_path = os.path.join(root, file)
# 计算相对路径
rel_path = os.path.relpath(root, input_dir) if recursive else ''
output_subdir = os.path.join(output_dir, rel_path)
if recursive and not os.path.exists(output_subdir):
os.makedirs(output_subdir)
xml_path = os.path.join(output_subdir, file.replace('.json', '.xml'))
print(f"转换: {json_path} -> {xml_path}")
try:
self.convert_file(json_path, xml_path)
except Exception as e:
print(f"转换失败 {json_path}: {str(e)}")
# 命令行使用示例
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='批量转换JSON为XML')
parser.add_argument('input_dir', help='输入JSON文件目录')
parser.add_argument('output_dir', help='输出XML文件目录')
parser.add_argument('--root', default='root', help='XML根节点名称')
parser.add_argument('--recursive', action='store_true', help='递归处理子目录')
args = parser.parse_args()
converter = JSON2XMLConverter(root_name=args.root)
converter.batch_convert(args.input_dir, args.output_dir, args.recursive)
安装所需库
pip install dicttoxml xmltodict
使用Node.js脚本
const fs = require('fs');
const path = require('path');
const convert = require('xml-js');
function jsonToXml(jsonFile, xmlFile) {
const jsonData = JSON.parse(fs.readFileSync(jsonFile, 'utf-8'));
const options = {
compact: true,
ignoreComment: true,
spaces: 4
};
const xml = convert.json2xml(jsonData, options);
fs.writeFileSync(xmlFile, xml, 'utf-8');
}
function batchConvert(inputDir, outputDir, recursive = false) {
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const items = fs.readdirSync(inputDir);
items.forEach(item => {
const fullPath = path.join(inputDir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory() && recursive) {
const subOutputDir = path.join(outputDir, item);
batchConvert(fullPath, subOutputDir, recursive);
} else if (item.endsWith('.json')) {
const xmlFile = path.join(outputDir, item.replace('.json', '.xml'));
console.log(`转换: ${item} -> ${path.basename(xmlFile)}`);
jsonToXml(fullPath, xmlFile);
}
});
}
// 使用
batchConvert('./json_files', './xml_files');
使用说明
-
准备环境:
# Python pip install dicttoxml xmltodict # Node.js npm install xml-js
-
运行脚本:
# Python高级版本 python converter.py ./input_json ./output_xml --root data --recursive # Node.js node converter.js
-
目录结构:
./project/ ├── json_files/ │ ├── file1.json │ ├── file2.json │ └── subdir/ │ └── file3.json └── xml_files/ ├── file1.xml ├── file2.xml └── subdir/ └── file3.xml
选择适合你需求的脚本,Python版本更稳定,Node.js版本处理大量文件时性能更好。