Created
March 5, 2022 09:17
-
-
Save rodrigo-x/7f1a5181d99ec401dfc08e4e05b3ffd7 to your computer and use it in GitHub Desktop.
This example was poorly written. So I decided to rewrite it here publicly at github.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env lua | |
-- Lib Expat example with cURL | |
local cURL = require "cURL" | |
local lxp = require "lxp" | |
tags = {} | |
items = {} | |
callback = {} | |
function callback.StartElement(parser, tagname) | |
tags[#tags + 1] = tagname | |
if (tagname == "item") then | |
items[#items + 1] = {} | |
end | |
end | |
function callback.CharacterData(parser, str) | |
if (tags[#tags -1] == "item") then | |
--we are parsing a item, get rid of trailing whitespace | |
items[#items][tags[#tags]] = string.gsub(str, "%s*$", "") | |
end | |
end | |
function callback.EndElement(parser, tagname) | |
--assuming well formed xml | |
tags[#tags] = nil | |
end | |
new_callback = lxp.new(callback) | |
-- create and setup easy handle | |
handle_curl = cURL.easy_init() | |
handle_curl:setopt_url("https://www.archlinux-br.org/feeds/news/") | |
multi = cURL.multi_init() | |
multi:add_handle(handle_curl) | |
for data, type in multi:perform() do | |
-- ign "header" | |
if (type == "data") then | |
assert(new_callback:parse(data)) | |
end | |
end | |
--finish document | |
assert(new_callback:parse()) | |
new_callback:close() | |
for i, item in ipairs(items) do | |
for keys, values in pairs(item) do | |
print(keys, values) | |
end | |
print() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment