json = require ("json") xml2lua = require("xml2lua") handler = require("xmlhandler.tree") local parser = xml2lua.parser(handler) -- 数据清洗函数(处理命名空间和空值)把 改成 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 = [[ SIMPLIFIED CHINESE 0 CBJJT1 北京京泰日晟科技有限公司 CBJJXK 北京吉鑫康商贸有限公司 ]] -- 执行解析 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 )