使用Python的XML更改标签名称


问题内容

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,则可以查找和是set的SSN子元素的所有元素。Employee``tag

例…

输入 (input.xml)

<Company>
    <Employee>
        <SSN>111111111</SSN>
        <Dependent>
            <SSN>222222222</SSN>
        </Dependent>
    </Employee>
</Company>

蟒蛇

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>