I have an XML file that looks like the code below:
<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129"callsign="wxman132" active="1" public="" gps="0" phone="" email="[email protected]" first="" last=""></spotter>
I've tried using dom.minidom, but how can I easily parse out the lat and lng variable values from the XML file?
Thanks for your help in advance!
You need to use an XML parser, like ElementTree, BeautifulSoup or lxml.
Here's an example using ElementTree from the standard library:
from xml.etree import ElementTree as ET
tree = ET.fromstring("""
<test>
<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129" callsign="wxman132" active="1" public="" gps="0" phone="" email="[email protected]" first="" last=""/>
</test>""")
spotter = tree.find('.//spotter')
print spotter.attrib['lat'], spotter.attrib['lng']
Here's an example using BeautifulSoup:
from bs4 import BeautifulSoup
data = '<spotter num="0187" report_at="2014-03-15 20:10:25" lat="49.8696518" lng="-80.0973129" callsign="wxman132" active="1" public="" gps="0" phone="" email="[email protected]" first="" last=""/>'
soup = BeautifulSoup(data)
spotter = soup.spotter
print spotter['lat'], spotter['lng']
Both print:
49.8696518 -80.0973129
BeautifulSoup is more forgiving, in terms of well-formed xml structure (see, I had to edit the xml a bit to make things work for ElementTree), and it's actually much easier to work with.
Hope that helps.
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