16.01.2019, 07:58
Since Expat library is stream-oriented, xpath cannot be used. Here's an example that parses the XML and retrieves the required fields:
Code:
require('socket.ftp')
data = socket.ftp.get('ftp://ftp.bom.gov.au/anon/gen/fwo/IDV10450.xml')
if not data then
log('Fetch failed to retrieve weather data')
return
end
aac = 'VIC_PT042'
forecast = {}
function starttag(p, tag, attrs)
if tag == 'area' and attrs.aac == aac then
in_area = true
elseif tag == 'forecast-period' and in_area then
index = tonumber(attrs.index)
if index then
forecast[ index ] = {}
end
elseif index then
prop = attrs.type
end
end
function endtag(p, tag)
if tag == 'area' then
in_area = false
elseif tag == 'forecast-period' then
index = nil
elseif index then
prop = nil
end
end
function text(p, txt)
if in_area and index and prop then
forecast[ index ][ prop ] = txt:trim()
end
end
require('lxp').new({
StartElement = starttag,
EndElement = endtag,
CharacterData = text,
}):parse(data)
Weather_Temp_Max = forecast[ 1 ].air_temperature_maximum
Weather_Temp_Min = forecast[ 1 ].air_temperature_minimum
Weather_Rain = forecast[ 1 ].probability_of_precipitation
-- remove percent sign from string
if Weather_Rain then
Weather_Rain = Weather_Rain:gsub('%%', '')
end
grp.write('1/1/100', Weather_Temp_Max)
grp.write('1/1/101', Weather_Temp_Min)
grp.write('1/1/102', Weather_Rain)