How in below example get NUM or CODE
lines = filename.split('\n')
for line in lines:
print("CODE is:" + ???);
#CODE is: 1111
#CODE is: 2222
#CODE is: 3333
file
<FROM ID="1610350010160016">
<PR NUM="1" CODE="1111" />
<PR NUM="2" CODE="2222" />
<PR NUM="3" CODE="3333" />
</FROM>
How get NUM and CODE from abowe example?
This is one way using regex:
import re
lines = filename.split('\n')
for line in lines:
print('NUM is : {}'.format(''.join(re.findall(r'NUM="(\w+)', line))), end=" ")
print('CODE is : {}'.format(''.join(re.findall(r'CODE="(\w+)', line))))
'''
NUM is : 1 CODE is : 1111
NUM is : 2 CODE is : 2222
NUM is : 3 CODE is : 3333
'''
You can use the standard library (Python 2.5+):
import xml.etree.ElementTree as ET
for element in ET.parse('data.xml').getroot():
print(element.attrib['NUM'], element.attrib['CODE'])
where data.xml contains the XML data.
If you have the data in a string, you can use the string parser instead:
ET.fromstring('Your XML data')
This solution doesn't use regex and is very compact and readable, and it works with any data type (for example, dates in the format 'gg.mm.aaaa').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With