Reputation: 89
I have a xml file as shown below:
<records>
<record>
<device_serial_number>PAD203146024</device_serial_number>
<device_serial_number_2>203146024</device_serial_number_2>
<docsis_mac>6412695EB9BB</docsis_mac>
</record>
<record>
<device_serial_number>PAD206024</device_serial_number>
<device_serial_number_2>20324</device_serial_number_2>
<docsis_mac>6412BB</docsis_mac>
</record>
</records>
I read this xml file using ETree in python and works well, now I want to check if tag has text starting with "PAD" if it has then output it as below:
Expected output
<record>
<device_serial_number>PAD203146024</device_serial_number>
<device_serial_number_2>203146024</device_serial_number_2>
<docsis_mac>6412695EB9BB</docsis_mac>
</record>
Upvotes: 0
Views: 49
Reputation: 2327
import xml.etree.ElementTree as ET
recs=[ET.tostring(c) for c in record if c.find('device_serial_number').text[:3]=='PAD']
for rec in recs:
print(rec)
where record
above is record
element in the for loop as shown in your question. This should return your records only if 'device_serial_number'
starts with PAD
as below:-
<record>
<device_serial_number>PAD203146024</device_serial_number>
<device_serial_number_2>203146024</device_serial_number_2>
<docsis_mac>6412695EB9BB</docsis_mac>
</record>
<record>
<device_serial_number>PAD206024</device_serial_number>
<device_serial_number_2>20324</device_serial_number_2>
<docsis_mac>6412BB</docsis_mac>
</record>
If any of the record elements do not have device_serial_number
as a child then I would use the below:
from xml.etree import ElementTree as ET
from xml.dom.minidom import parseString
tree = ET.parse('C:\\Use\\CO.xml')
root = tree.getroot()
for record in root.findall('records'):
recs=[c for c in t if c.find('device_serial_number')!=None and c.find('device_serial_number').text[:3]=='PAD']
for rec in recs:
print(parseString(ET.tostring(rec)).toprettyxml(''))
Upvotes: 1