fy36
2025-07-01 350eb5ec9163d3ea21416b1525bb80191e958071
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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