本文目录导读:

我来介绍几种常见的XML格式转换脚本编写方法。
使用Python的lxml库
基本格式转换脚本
from lxml import etree
import os
def convert_xml_format(input_file, output_file, transformation_type='rename_tag'):
"""
XML格式转换示例
"""
# 解析XML
tree = etree.parse(input_file)
root = tree.getroot()
# 不同类型的转换
if transformation_type == 'rename_tag':
# 重命名标签
for elem in root.iter():
if elem.tag == 'old_tag':
elem.tag = 'new_tag'
elif transformation_type == 'add_attribute':
# 添加属性
for elem in root.iter():
if elem.get('id') is None:
elem.set('type', 'default')
elif transformation_type == 'restructure':
# 重构结构
parent_map = {c:p for p in root.iter() for c in p}
# 这里实现特定结构的转换逻辑
# 保存转换后的XML
tree.write(output_file, encoding='utf-8', xml_declaration=True)
print(f"转换完成: {output_file}")
# 使用XSLT进行复杂转换
def xslt_transform(xml_file, xslt_file, output_file):
"""
使用XSLT样式表转换XML
"""
# 加载XML和XSLT
xml_tree = etree.parse(xml_file)
xslt_tree = etree.parse(xslt_file)
# 创建转换器
transform = etree.XSLT(xslt_tree)
# 执行转换
result = transform(xml_tree)
# 保存结果
result.write(output_file, encoding='utf-8', xml_declaration=True)
# 批量转换
def batch_convert(input_dir, output_dir, pattern='*.xml'):
"""
批量转换XML文件
"""
import glob
os.makedirs(output_dir, exist_ok=True)
for xml_file in glob.glob(os.path.join(input_dir, pattern)):
filename = os.path.basename(xml_file)
output_file = os.path.join(output_dir, filename)
convert_xml_format(xml_file, output_file)
XSLT样式表示例
创建XSLT文件 transform.xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- 转换所有元素 -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- 重命名特定标签 -->
<xsl:template match="old_element_name">
<new_element_name>
<xsl:apply-templates select="@*|node()"/>
</new_element_name>
</xsl:template>
<!-- 移除特定元素 -->
<xsl:template match="element_to_remove"/>
<!-- 添加新元素 -->
<xsl:template match="parent_element">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:if test="not(child_element)">
<xsl:element name="new_child">
<xsl:text>default_value</xsl:text>
</xsl:element>
</xsl:if>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<!-- 转换属性格式 -->
<xsl:template match="attribute">
<xsl:attribute name="new_{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
使用Java进行XML转换
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.*;
public class XMLConverter {
public static void transformXML(String xmlPath, String xsltPath, String outputPath)
throws TransformerException {
// 创建TransformerFactory
TransformerFactory factory = TransformerFactory.newInstance();
// 加载XSLT样式表
Source xsltSource = new StreamSource(new File(xsltPath));
Transformer transformer = factory.newTransformer(xsltSource);
// 设置参数
transformer.setParameter("param1", "value1");
// 执行转换
Source xmlSource = new StreamSource(new File(xmlPath));
Result output = new StreamResult(new File(outputPath));
transformer.transform(xmlSource, output);
}
// DOM方式转换
public static void domTransform(File inputFile, File outputFile) {
try {
// 解析XML
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(inputFile);
// 修改文档结构
modifyDocument(doc);
// 保存转换结果
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(doc), new StreamResult(outputFile));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void modifyDocument(Document doc) {
// 这里实现特定的转换逻辑
// 重命名元素、添加属性、重组结构等
}
}
使用命令行工具
xmllint(Linux/Mac)
# 使用XSLT转换 xmllint --xslt transform.xslt input.xml > output.xml # 格式化XML xmllint --format input.xml > output.xml # 验证XML并输出格式化的版本 xmllint --valid --format input.xml > output.xml
XMLStarlet
# 替换标签名 xml ed -O -R "old_tag:new_tag" input.xml > output.xml # 删除元素 xml ed -d "//element_to_delete" input.xml > output.xml # 添加属性 xml ed -a "//parent" -t attr -n "new_attribute" -v "value" input.xml > output.xml
Shell脚本批量转换
#!/bin/bash
# 批量XML转换脚本
INPUT_DIR="./xml_input"
OUTPUT_DIR="./xml_output"
XSLT_FILE="./transform.xslt"
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 批量转换
for xml_file in "$INPUT_DIR"/*.xml; do
if [ -f "$xml_file" ]; then
filename=$(basename "$xml_file")
output_file="$OUTPUT_DIR/$filename"
echo "转换文件: $filename"
# 使用xsltproc转换
xsltproc -o "$output_file" "$XSLT_FILE" "$xml_file"
# 或者使用Python脚本
# python3 xml_converter.py "$xml_file" "$output_file"
fi
done
echo "所有文件转换完成!"
常用转换模式示例
# 1. 扁平化结构转换
def flatten_structure(root):
"""将嵌套结构展平"""
result = etree.Element("flattened")
for elem in root.iter():
if elem.text and elem.text.strip():
new_elem = etree.SubElement(result, elem.tag)
new_elem.text = elem.text
return result
# 2. 合并多个XML文件
def merge_xml_files(file_list, output_file):
"""合并多个XML文件"""
combined = etree.Element("root")
for file in file_list:
tree = etree.parse(file)
combined.append(tree.getroot())
# 保存合并后的文件
result_tree = etree.ElementTree(combined)
result_tree.write(output_file, encoding='utf-8', xml_declaration=True)
# 3. 转换为JSON格式
def xml_to_json(xml_file):
"""将XML转换为JSON"""
import json
from xmltodict import parse
with open(xml_file, 'r', encoding='utf-8') as f:
xml_content = f.read()
dict_data = parse(xml_content)
return json.dumps(dict_data, indent=2, ensure_ascii=False)
这些脚本和方法可以帮助你实现各种XML格式的转换需求,根据具体场景选择合适的方案。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播