XML change tag name using Python

前端 未结 1 1686
花落未央
花落未央 2021-01-06 19:13

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:


   <         


        
相关标签:
1条回答
  • 2021-01-06 20:13

    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>
    
    0 讨论(0)
提交回复
热议问题