I am very, very new to Python so please be kind!
I have created a test file in XML which has a list of fake customers and their associated telephone numbers. This was manually produced and took a fair while! I'm hoping to create an automated solution in Python to replace the first digit of the customer_ID (stored as an attribute within the XML) and generate a new XML.
After a few hours reading and developing here is my code;
# Python code for test data generation
import re
import xml.etree.ElementTree as ET
tree = ET.parse('Junk\\Test_File.xml')
root = tree.getroot()
for child in tree.iter():
Cust_ID = re.findall('([0-9]{10})', child.text)
A = [Cust_ID.replace(Cust_ID[0],'1') for Cust_ID in Cust_IDs]
print(A)
tree.write('Junk\\New.xml')
So far I can isolate the list of Customer IDs as Cust_ID and replace the first digit as required. My issue is writing these new values in my output.
Given how junior I am to this code I'm not 100% I'm on the right path so any pointers to a more complete solution (if there is one) would also be appreciated.
Many thanks
These day most people use libraries you have a number of choices.
2 I've used
CElementTree
import xml.etree.cElementTree as ET root = ET.Element("root") file = ET.SubElement(root, "file") ET.SubElement(file, "fieldone", name="1").text = "something1" ET.SubElement(file, "field2two", name="2").text = "something2" tree = ET.ElementTree(root) tree.write("file.xml")
Here are some useful documentation links
http://effbot.org/zone/element-index.htm
https://docs.python.org/3/library/xml.etree.elementtree.html
Be aware xml.etree.ElementTree
isn't secure
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.