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:
111111111
222222222
I want to change the tag under the Employee to 'EESSN' and leave the tag under the Dependent the same. To look like this.
111111111
222222222
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!
asked Feb 20, 2019 at 22:14
2
If you want to use ElementTree, you can find all SSN
elements that are children of Employee
and set tag
.
Example...
Input [input.xml]
111111111
222222222
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]
111111111
222222222
answered Feb 21, 2019 at 15:20
Daniel HaleyDaniel Haley
49.7k6 gold badges68 silver badges90 bronze badges
2
Questions : XML change tag name using Python
2022-09-26T14:04:47+00:00 2022-09-26T14:04:47+00:00
871
Very new to XML and Python. I want to change anycodings_xml the tag names of certain elements in an XML anycodings_xml document. Here's how the document looks now:
111111111
222222222
I want to change the tag under the Employee anycodings_xml to 'EESSN' and leave the tag under the anycodings_xml Dependent the same. To look like this.
111111111
222222222
The document includes hundreds of companies anycodings_xml and thousands of employees both with tens to anycodings_xml hundreds of sub elements, so a find and anycodings_xml replace option is what I believe I need.
I want to use ElementTree module. The only anycodings_xml code I have that is working is the importing anycodings_xml the data and writing it to a new file. anycodings_xml Thanks for all your help!
Total Answers 1
33
Answers 1 : of XML change tag name using Python
If you want to use ElementTree, you can anycodings_xml find all SSN elements that are children anycodings_xml of Employee and set tag.
Example...
Input [input.xml]
111111111
222222222
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]
111111111
222222222
0
2022-09-26T14:04:47+00:00 2022-09-26T14:04:47+00:00Answer Link
mRahman