pip install xmltodict
Requirement already satisfied: xmltodict in c:\users\asmaliza\appdata\local\programs\python\python39\lib\site-packages (0.12.0) Note: you may need to restart the kernel to use updated packages.
import pandas as pd
import xmltodict
# load the xml
data = xmltodict.parse(open("data/observations_01.xml").read())
data
OrderedDict([('dwml',
OrderedDict([('@xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'),
('@xmlns:xsi',
'http://www.w3.org/2001/XMLSchema-instance'),
('@version', '1.0'),
('@xsi:noNamespaceSchemaLocation',
'http://www.nws.noaa.gov/forecasts/xml/DWMLgen/schema/DWML.xsd'),
('head',
OrderedDict([('product',
OrderedDict([('@srsName',
'WGS 1984'),
('@concise-name',
'glance'),
('@operational-mode',
'official'),
('title',
"NOAA's National Weather Service Forecast at a Glance"),
('field',
'meteorological'),
('category',
'forecast'),
('creation-date',
OrderedDict([('@refresh-frequency',
'PT1H'),
('#text',
'2017-01-08T02:52:41Z')]))])),
('source',
OrderedDict([('more-information',
'http://www.nws.noaa.gov/forecasts/xml/'),
('production-center',
OrderedDict([('sub-center',
'Product Generation Branch'),
('#text',
'Meteorological Development Laboratory')])),
('disclaimer',
'http://www.nws.noaa.gov/disclaimer.html'),
('credit',
'http://www.weather.gov/'),
('credit-logo',
'http://www.weather.gov/images/xml_logo.gif'),
('feedback',
'http://www.weather.gov/feedback.php')]))])),
('data',
OrderedDict([('location',
OrderedDict([('location-key',
'point1'),
('point',
OrderedDict([('@latitude',
'41.78'),
('@longitude',
'-88.65')]))]))]))]))])
# get the value of location-key
data['dwml']['data']
OrderedDict([('location',
OrderedDict([('location-key', 'point1'),
('point',
OrderedDict([('@latitude', '41.78'),
('@longitude', '-88.65')]))]))])
data['dwml']['data']['location']['location-key']
'point1'
data['dwml']['data']['location']['point']['@latitude']
'41.78'
data['dwml']['data']['location']['point']['@longitude']
'-88.65'
Call remote service and download xml content
import requests
response = requests.get("https://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?whichClient=NDFDgen&lat=41.87&lon=+-87.65&product=glance")
response
<Response [200]>
# convert response to xml
data = xmltodict.parse(response.text)
# write returned data to external file
with open('result.xml', 'w') as result_file :
result_file.write(xmltodict.unparse(data))
# start processing the data
data['dwml']['data']['location']['location-key']
'point1'
data['dwml']['data']['location']['point']
OrderedDict([('@latitude', '41.87'), ('@longitude', '-87.65')])
data['dwml']['data']['location']['point']['@latitude']
'41.87'