批量处理XML文件可通过Python脚本提取数据、转换格式或合并文件,例如用ElementTree解析XML并结合os模块遍历目录,实现批量提取标题写入CSV、转为JSON、使用XSLT转HTML及多文件合并,关键在于明确需求后选择合适方法。

批量处理 XML 文件通常涉及转换格式、提取数据、合并文件或验证结构等操作。使用脚本可以高效完成这些任务。下面介绍几种常见的批量处理方式和对应脚本示例。
示例:批量读取 XML 文件并提取特定字段(如标题)
假设你有一批 .xml 文件,想提取每个文件中的 <title> 内容并保存到 CSV:import os
import xml.etree.ElementTree as ET
import csv
folder_path = 'xml_files' # XML 文件所在目录
output_file = 'titles.csv'
with open(output_file, 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Filename', 'Title']) # 表头
for filename in os.listdir(folder_path):
if filename.endswith('.xml'):
file_path = os.path.join(folder_path, filename)
try:
tree = ET.parse(file_path)
root = tree.getroot()
title_elem = root.find('title') # 根据实际结构调整路径
title = title_elem.text if title_elem is not None else 'Not found'
writer.writerow([filename, title])
except Exception as e:
writer.writerow([filename, f'Error: {e}'])将此脚本保存为 extract_titles.py,把所有 XML 文件放入 xml_files 文件夹即可运行。
import os
import xml.etree.ElementTree as ET
import json
def xml_to_dict(element):
data = {}
if element.text and element.text.strip():
return element.text
for child in element:
child_data = xml_to_dict(child)
if child.tag in data:
if not isinstance(data[child.tag], list):
data[child.tag] = [data[child.tag]]
data[child.tag].append(child_data)
else:
data[child.tag] = child_data
return data
folder_path = 'xml_files'
output_folder = 'json_output'
os.makedirs(output_folder, exist_ok=True)
for filename in os.listdir(folder_path):
if filename.endswith('.xml'):
file_path = os.path.join(folder_path, filename)
try:
tree = ET.parse(file_path)
root = tree.getroot()
data = {root.tag: xml_to_dict(root)}
json_filename = filename.replace('.xml', '.json')
output_path = os.path.join(output_folder, json_filename)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
except Exception as e:
print(f"Failed to convert {filename}: {e}")前提:安装 xsltproc
Ubuntu/Debian: sudo apt install xsltproc示例:批量将 XML 转为 HTML
创建 XSL 文件 transform.xsl:<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h1><xsl:value-of select="data/title"/></h1>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Shell 脚本(batch_xml.sh):
#!/bin/bash
for file in xml_files/*.xml; do
base=$(basename "$file" .xml)
xsltproc transform.xsl "$file" > "html_output/${base}.html"
done运行前赋予执行权限:chmod +x batch_xml.sh
import os
import xml.etree.ElementTree as ET
# 创建根节点
merged_root = ET.Element("MergedData")
folder_path = 'xml_files'
for filename in os.listdir(folder_path):
if filename.endswith('.xml'):
file_path = os.path.join(folder_path, filename)
try:
tree = ET.parse(file_path)
root = tree.getroot()
# 将原根节点作为子节点加入
merged_root.append(root)
except Exception as e:
print(f"Error parsing {filename}: {e}")
# 保存合并后的文件
merged_tree = ET.ElementTree(merged_root)
merged_tree.write('merged.xml', encoding='utf-8', xml_declaration=True)基本上就这些常见场景。根据你的具体需求调整标签名、路径和输出格式即可。关键是先明确“你要对 XML 做什么”,再选择合适的工具和脚本结构。
以上就是xml文件怎么批量转换 批量处理xml文件的脚本的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号