1
Jianw
9 天以前 70f29da38121b9a467841253e3268feb5df02902
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
json  = require ("json")
xml2lua = require("xml2lua")
handler = require("xmlhandler.tree")
local parser = xml2lua.parser(handler)
 
-- 数据清洗函数(处理命名空间和空值)把 <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:", "")
            
            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
        return result
    end
    return process(data)
end
 
local 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
 
local soap_xml = [[
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <v1:InCompanyReq xmlns:v1="http://www.gkht.com/Information/INV/Ebs/Schemas/InCompany/V1.0">
      <v1:Company_Input>
        <v1:RESTHeader>
          <v1:NLSLanguage>SIMPLIFIED CHINESE</v1:NLSLanguage>
          <v1:Org_Id>0</v1:Org_Id>
        </v1:RESTHeader>
        <v1:InputParameters>
          <v1:COMPANY_TB>
            <v1:COMPANY_TB_ITEM>
              <v1:companyCode>CBJJT1</v1:companyCode>
              <v1:companyName>北京京泰日晟科技有限公司</v1:companyName>
              <v1:memo>个</v1:memo>
            </v1:COMPANY_TB_ITEM>
            <v1:COMPANY_TB_ITEM>
              <v1:companyCode>CBJJXK</v1:companyCode>
              <v1:companyName>北京吉鑫康商贸有限公司</v1:companyName>
              <v1:memo>个</v1:memo>
            </v1:COMPANY_TB_ITEM>
          </v1:COMPANY_TB>
        </v1:InputParameters>
      </v1:Company_Input>
    </v1:InCompanyReq>
  </soap:Body>
</soap:Envelope>
]]
-- 执行解析
local parsed_data
nRet, parsed_data = xml_parse(soap_xml)
if ( nRet ~= 0 ) then return end
local input_parameter = parsed_data.Envelope.Body.InCompanyReq.Company_Input.InputParameters
 
local json_str = json.encode(input_parameter)
print( json_str )