Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parse XML variables from a single tag

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!

like image 915
wuffwuff Avatar asked Mar 27 '26 13:03

wuffwuff


1 Answers

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.

like image 193
alecxe Avatar answered Mar 29 '26 03:03

alecxe