使用 Python 更改 XML 标记名称 [英] XML change tag name using Python
问题描述
对 XML 和 Python 非常陌生.我想更改 XML 文档中某些元素的标签名称.这是文档现在的样子:
Very new to XML and Python. I want to change the tag names of certain elements in an XML document. Here's how the document looks now:
<Company>
<Employee>
<SSN>111111111</SSN>
<Dependent>
<SSN>222222222</SSN>
我想将 Employee 下的标签更改为EESSN",并使 Dependent 下的标签保持不变.看起来像这样.
I want to change the tag under the Employee to 'EESSN' and leave the tag under the Dependent the same. To look like this.
<Company>
<Employee>
<EESSN>111111111</EESSN>
<Dependent>
<SSN>222222222</SSN>
该文档包含数百家公司和数千名员工,并包含数十到数百个子元素,因此我认为我需要查找和替换选项.
The document includes hundreds of companies and thousands of employees both with tens to hundreds of sub elements, so a find and replace option is what I believe I need.
我想使用 ElementTree 模块.我唯一可以使用的代码是导入数据并将其写入新文件.感谢您的帮助!
I want to use ElementTree module. The only code I have that is working is the importing the data and writing it to a new file. Thanks for all your help!
推荐答案
如果您想使用 ElementTree,您可以找到所有 Employee
子元素的 SSN
元素和设置标签
.
If you want to use ElementTree, you can find all SSN
elements that are children of Employee
and set tag
.
示例...
输入 (input.xml)
Input (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)
Output (output.xml)
<Company>
<Employee>
<EESSN>111111111</EESSN>
<Dependent>
<SSN>222222222</SSN>
</Dependent>
</Employee>
</Company>
这篇关于使用 Python 更改 XML 标记名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!