XML change tag name using Python

喜欢而已 提交于 2019-12-20 06:39:43

问题


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>

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.

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!


回答1:


If you want to use ElementTree, you can find all SSN elements that are children of Employee and set tag.

Example...

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 (output.xml)

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


来源:https://stackoverflow.com/questions/54796054/xml-change-tag-name-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!