xml2lua = require("xml2lua")
|
handler = require("xmlhandler.tree")
|
local parser = xml2lua.parser(handler)
|
|
local xml = {_version = "0.1.1"} -- 定义一个空表,用于存储模块的函数和变量'
|
|
-- 数据清洗函数(处理命名空间和空值)把 <soap:Body> 改成 <Body>
|
local function clean_data(data)
|
local function process(tbl)
|
local result = {}
|
for k, v in pairs(tbl) do
|
-- 去除命名空间前缀[6,9](@ref)
|
local new_key = k:gsub("v1:", ""):gsub("soap:", ""):gsub("soapenv:", "")
|
|
if type(v) == "table" then
|
-- 处理数组结构[4](@ref)
|
if #v > 0 then
|
local arr = {}
|
for i, item in ipairs(v) do
|
arr[i] = process(item)
|
end
|
result[new_key] = arr
|
else
|
result[new_key] = process(v)
|
end
|
else
|
result[new_key] = v ~= "" and v or nil
|
end
|
end
|
if next(result) == nil then result = "" end
|
return result
|
end
|
return process(data)
|
end
|
|
function xml.parse(xml_str)
|
local ok, err = pcall(function()
|
parser:parse(xml_str) -- 使用 pcall 捕获异常[7](@ref)
|
end)
|
if not ok then
|
return 1, "XML解析失败:"..err
|
end
|
return 0, clean_data( handler.root )
|
end
|
|
return xml
|