对于 XML 和 Python 来说非常陌生。我想更改 XML 文档中某些元素的标签名称。该文档现在的样子如下:
<Company>
<Employee>
<SSN>111111111</SSN>
<Dependent>
<SSN>222222222</SSN>
我想将 Employee 下的标签更改为“EESSN”,并保留 Dependent 下的标签不变。看起来像这样。
<Company>
<Employee>
<EESSN>111111111</EESSN>
<Dependent>
<SSN>222222222</SSN>
该文档包括数百家公司和数千名员工,都有数十到数百个子元素,因此我认为我需要查找和替换选项。
我想使用 ElementTree 模块。我唯一有效的代码是导入数据并将其写入新文件。感谢你的帮助!
如果你想使用ElementTree,你可以找到所有SSN
的子元素Employee
并设置tag
.
例子...
Input(输入.xml)
<Company>
<Employee>
<SSN>111111111</SSN>
<Dependent>
<SSN>222222222</SSN>
</Dependent>
</Employee>
</Company>
Python
import xml.etree.ElementTree as ET
tree = ET.parse("input.xml")
for elem in tree.findall("Employee/SSN"):
elem.tag = "EESSN"
tree.write("output.xml")
Output(输出.xml)
<Company>
<Employee>
<EESSN>111111111</EESSN>
<Dependent>
<SSN>222222222</SSN>
</Dependent>
</Employee>
</Company>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)