批量提取数千XML文件中引用的CGM图形及来源文件需求
批量提取XML文件中引用的图形文件列表
针对你数千份XML文件提取图形引用的需求,下面提供两种高效的批量处理方案,无需逐个手动操作:
方案1:Python脚本(跨平台,灵活可控)
这个方案适合有基础Python环境的用户,能精准提取图形文件名和对应XML来源,结果可直接导出为CSV方便Excel处理。
import os import xml.etree.ElementTree as ET import csv def extract_graphic_files(root_dir, output_csv): # 准备CSV写入器 with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile: fieldnames = ['xml_file', 'graphic_filename', 'full_path'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() # 遍历目录下所有XML文件 for dirpath, _, filenames in os.walk(root_dir): for filename in filenames: if filename.lower().endswith('.xml'): xml_path = os.path.join(dirpath, filename) try: # 解析XML tree = ET.parse(xml_path) root = tree.getroot() # 查找所有<graphic>节点 for graphic in root.findall('.//graphic'): file_attr = graphic.get('file') if file_attr: # 提取文件名 graphic_filename = os.path.basename(file_attr) # 写入CSV writer.writerow({ 'xml_file': xml_path, 'graphic_filename': graphic_filename.lower(), 'full_path': file_attr }) except Exception as e: print(f"处理文件出错 {xml_path}: {str(e)}") # 配置参数:替换为你的XML文件根目录和输出CSV路径 extract_graphic_files(r'C:\Your\XML\Directory', 'graphic_references.csv')
使用步骤:
- 确保安装了Python(3.x版本均可)
- 将上述代码保存为
extract_graphics.py - 修改代码中
root_dir和output_csv的路径为你的实际路径 - 打开命令行,运行
python extract_graphics.py - 生成的
graphic_references.csv可直接用Excel打开,查看所有图形引用及来源
方案2:PowerShell命令(Windows环境无需额外安装)
如果是Windows用户,直接用PowerShell就能快速处理,无需安装额外工具:
# 替换为你的XML文件根目录 $xmlDir = "C:\Your\XML\Directory" # 输出CSV路径 $outputCsv = "graphic_references.csv" Get-ChildItem -Path $xmlDir -Filter *.xml -Recurse | ForEach-Object { $xmlPath = $_.FullName try { $xml = [xml](Get-Content $xmlPath -Encoding UTF8) $xml.SelectNodes("//graphic") | ForEach-Object { $filePath = $_.file if ($filePath) { [PSCustomObject]@{ xml_file = $xmlPath graphic_filename = [System.IO.Path]::GetFileName($filePath) full_path = $filePath } } } } catch { Write-Warning "处理文件出错 $xmlPath : $_" } } | Export-Csv -Path $outputCsv -NoTypeInformation -Encoding UTF8
使用步骤:
- 打开PowerShell
- 将上述命令中的
$xmlDir和$outputCsv替换为你的实际路径 - 粘贴命令并执行
- 生成的CSV文件可直接导入Excel
注意事项:
如果你的XML文件包含命名空间,需要修改XPath查询语句。比如假设命名空间为http://example.com/ns,Python中需要先注册命名空间:
ET.register_namespace('', 'http://example.com/ns') # 然后查找节点时用带命名空间的XPath root.findall('.//{http://example.com/ns}graphic')
PowerShell中则需要调整SelectNodes的参数:
$ns = New-Object Xml.XmlNamespaceManager($xml.NameTable) $ns.AddNamespace("ns", "http://example.com/ns") $xml.SelectNodes("//ns:graphic", $ns)
内容的提问来源于stack exchange,提问作者Ruth Cundy
相关产品推荐
相关产品推荐

