<sourceImageInformation>
<fileName> </fileName>
</sourceImageInformation>
我想(递归)处理所有xml文件,并在标签之间添加tiff名称。 xml的基本名称与tiff相同。最好的方法是什么?我应该将bash与find和sed一起使用,还是将Python与string.replace一起使用,还是有更好的选择?
not使用字符串处理工具来处理XML! XML不是常规格式,使用str.replace()
或sed
或任何此类工具可能会导致误报和错误。
xml.etree.ElementTree
,它使此任务足够简单:xml.etree.ElementTree
上面处理给定目录中的所有XML文件(使用from pathlib import Path from xml.etree import ElementTree as ET for xmlfile in Path("directory_with_xml_files").glob("*.xml"): tree = ET.parse(xmlfile) namespace = tree.getroot().tag.partition('}')[0][1:] elem = tree.find(f".//{{{namespace}}}fileName") elem.text = f"{xmlfile.stem}.tiff" tree.write(xmlfile, encoding="UTF-8", xml_declaration=True)
,使用pathlib
module查找XML文件)。对于每个文件,它将XML数据解析为XML树,并使用该元素的简单pathlib
,Path.glob()
method(使用Path.glob()
,这是该元素的基本名称)在树中找到第一个<fileName>
元素XPath expression扩展名)并将XML树写回到原始文件。您说过您使用了updates the text,它使用filename stem来区分版本;以上应该从根元素中选择要使用的正确名称空间。
演示:
.xml