这几天刚接到一个任务:要将xml配置文件转成可以直接读写的lua文件,方便在lua程序中直接调用,废话不多说直接上代码

(xmZMlua.lua文件)

saveDirPath = "/xxx/"   --- 保存转好的lua文件路劲(其中xxx代表的是路径,下同)
xmlDirPath  = "/xxx/" --- 待转的xml文件路径
require "lfs"
function SaveTableContent(file, obj)local szType = type(obj);if szType == "number" thenfile:write(obj);elseif szType == "string" thenfile:write(string.format("%q", obj));elseif szType == "table" then--把table的内容格式化写入文件-- print(obj.nodeFlag)if obj.nodeFlag ~= nil thenif obj:numProperties() == 0 and obj:numChildren() == 0 then SaveTableContent(file, obj:value() or "");elsefile:write("{");if obj:numProperties() ~= 0 then-- print(obj)file:write("[\"$\"]={");local pTable = {}local properties = obj:properties()for i=1, #properties dolocal propertie = properties[i]local propertieName  = propertie.namelocal propertieValue = propertie.value-- print("")file:write("[");SaveTableContent(file, propertieName);file:write("]=");SaveTableContent(file, propertieValue);if i ~= #properties then file:write(", ") endendfile:write("}");if obj:numChildren() ~= 0 then file:write(",") endendif obj:numChildren() ~= 0 then-- print("numChildren:"..tostring(obj:numChildren()))local allChildrenTable = {}local children = obj:children()local nextChildName = ""local lastChildName = ""for i=1,obj:numChildren() dolocal child = children[i]     nextChildName = child:name()-- print("lastChildName1-----------:"..lastChildName)if nextChildName ~= lastChildName then-- print("lastChildName2-----------:"..lastChildName)allChildrenTable[nextChildName] = {}lastChildName = nextChildName-- print("lastChildName4-----------:"..lastChildName)endtable.insert(allChildrenTable[nextChildName], child)endfor i,v in pairs(allChildrenTable) dofile:write("[");SaveTableContent(file, i);file:write("]=");SaveTableContent(file, v);file:write(", ");-- print("key:"..i..#v)end-- SaveTableContent(file, allChildrenTable, fileName);endfile:write("}");endelsefile:write("{");for i, v in pairs(obj) dolocal vType = type(v)if vType ~= "function" thenfile:write("[");SaveTableContent(file, i);file:write("]=");SaveTableContent(file, v );file:write(", ");endendfile:write("}");endelse-- error("can't serialize a "..szType);end
endfunction SaveTable(fileName,obj)-- print(path);-- printLog();local fileNewName = string.gsub(fileName, ".xml", ".lua");local savePath = saveDirPath..fileNewNamelocal file = io.open(savePath, "w");file:write("local "..string.gsub(fileName, ".xml", "").." = \n");-- print(fileName);SaveTableContent(file, obj);file:write("\nreturn  "..string.gsub(fileName, ".xml", "") );file:close();
end
function newParser()XmlParser = {};function XmlParser:ToXmlString(value)value = string.gsub(value, "&", "&"); -- '&' -> "&"value = string.gsub(value, "<", "<"); -- '<' -> "<"value = string.gsub(value, ">", ">"); -- '>' -> ">"value = string.gsub(value, "\"", """); -- '"' -> """value = string.gsub(value, "([^%w%&%;%p%\t% ])",function(c)print("c::::------->>>>>"..string.byte(c))return string.format("&#x%X;", string.byte(c))end);return value;endfunction XmlParser:FromXmlString(value)value = string.gsub(value, "&#x([%x]+)%;",function(h)print("h::::------->>>>>"..string.char(tonumber(h, 16)))return string.char(tonumber(h, 16))end);value = string.gsub(value, "&#([0-9]+)%;",function(h)print("h::::------->>>>>"..string.char(tonumber(h, 10)))return string.char(tonumber(h, 10))end);value = string.gsub(value, """, "\"");value = string.gsub(value, "'", "'");value = string.gsub(value, ">", ">");value = string.gsub(value, "<", "<");value = string.gsub(value, "&", "&");return value;endfunction XmlParser:ParseArgs(node, s)string.gsub(s, "(%w+)=([\"'])(.-)%2", function(w, _, a)node:addProperty(w, self:FromXmlString(a))end)endfunction XmlParser:ParseXmlText(xmlText)local stack = {}local top = newNode()table.insert(stack, top)local ni, c, label, xarg, emptylocal i, j = 1, 1while true doni, j, c, label, xarg, empty = string.find(xmlText, "<(%/?)([%w_:]+)(.-)(%/?)>", i)if not ni then break endlocal text = string.sub(xmlText, i, ni - 1);if not string.find(text, "^%s*$") thenlocal lVal = (top:value() or "") .. self:FromXmlString(text)stack[#stack]:setValue(lVal)endif empty == "/" then -- empty element taglocal lNode = newNode(label)self:ParseArgs(lNode, xarg)top:addChild(lNode)elseif c == "" then -- start taglocal lNode = newNode(label)self:ParseArgs(lNode, xarg)table.insert(stack, lNode)top = lNodeelse -- end taglocal toclose = table.remove(stack) -- remove toptop = stack[#stack]if #stack < 1 thenerror("XmlParser: nothing to close with " .. label)endif toclose:name() ~= label thenerror("XmlParser: trying to close " .. toclose.name .. " with " .. label)endtop:addChild(toclose)endi = j + 1endlocal text = string.sub(xmlText, i);if #stack > 1 thenerror("XmlParser: unclosed " .. stack[#stack]:name())endreturn topendfunction XmlParser:loadFile(xmlFilename, base)if not base thenbase = system.ResourceDirectoryendlocal path = system.pathForFile(xmlFilename, base)local hFile, err = io.open(path, "r");if hFile and not err thenlocal xmlText = hFile:read("*a"); -- read file contentio.close(hFile);return self:ParseXmlText(xmlText), nil;elseprint(err)return nilendendreturn XmlParser
endfunction newNode(name)local node = {}node.___nodeFlag = truenode.___value = nilnode.___name = namenode.___children = {}node.___props = {}function node:nodeFlag() return self.___nodeFlag endfunction node:value() return self.___value endfunction node:setValue(val) self.___value = val endfunction node:name() return self.___name endfunction node:setName(name) self.___name = name endfunction node:children() return self.___children endfunction node:numChildren() return #self.___children endfunction node:addChild(child)if self[child:name()] ~= nil thenif type(self[child:name()].name) == "function" thenlocal tempTable = {}table.insert(tempTable, self[child:name()])self[child:name()] = tempTableendtable.insert(self[child:name()], child)elseself[child:name()] = childendtable.insert(self.___children, child)endfunction node:properties() return self.___props endfunction node:numProperties() return #self.___props endfunction node:addProperty(name, value)local lName = "@" .. nameif self[lName] ~= nil thenif type(self[lName]) == "string" thenlocal tempTable = {}table.insert(tempTable, self[lName])self[lName] = tempTableendtable.insert(self[lName], value)elseself[lName] = valueendtable.insert(self.___props, { name = name, value = value })endreturn node
endfunction getpathes(rootpath, pathes)pathes = pathes or {}ret, files, iter = pcall(lfs.dir, rootpath)if ret == false thenreturn pathesendfor entry in files, iter dolocal next = falseif entry ~= '.' and entry ~= '..' thenlocal path = rootpath .. entry-- print (path)local attr = lfs.attributes(path)if attr == nil thennext = trueendif next == false then if attr.mode == 'directory' thengetpathes(path, pathes)else--进行数据组织i, j =string.find(path,"%.xml")if i ~= nil thenlocal hFile, err = io.open(path, "r");if hFile and not err thenlocal xmlText = hFile:read("*a"); -- read file contentio.close(hFile);-- xmlText = string.gsub(xmlText, "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "")xmlText = string.gsub(xmlText, "<!%-%-(.-)%-%->", "")-- print("xmlText:"..xmlText)local textObj = parser.ParseXmlText(parser, xmlText)SaveTable(entry, textObj);--local flag = true--for i,v in ipairs(exclude2MapArr) do--      if v == string.gsub(entry, ".xml", "") then--          flag = false--          break--      end--end--if flag then createSimpleXml(entry , dofile(saveDirPath..string.gsub(entry, ".xml", ".lua"))); endprint(entry.."-------------------->"..string.gsub(entry, ".xml", ".lua"))-- return xmlSimple.ParseXmlText(xmlText), nil;endendendendendnext = falseendreturn pathes
end-- function createSimpleXml(entry, obj)
--     -- name = name.split('_')[0];
--     local name =  string.upper(string.sub(entry, 1, 1))..string.sub(entry, 2, string.len(entry));
--     name = string.gsub(name, ".xml", "")
--     -- print('data[name]:'..obj[name..'s']..'----------------');
--     local arr = obj[name..'s'][1][name];
--     local map = {};
--     print('===========[ '..name..' ] ==========');
--     if name == 'Lang' then
--         for i=1,#arr do
--             map[tostring(arr[i]['$']['key'])] = arr[i];
--         end
--     else
--         for i=1,#arr do
--             map[tostring(arr[i]['$']['id'])] = arr[i];
--         end--     end
--     SaveTable(entry, map);
--     -- return map;
-- endif lfs == nil then return endpathes = {}
parser = newParser()
getpathes(xmlDirPath, pathes)

这其中应用到了“lfs”依赖库,它的全名是“luafilesystem”;要安装它分两步

1)首先必须安装“lua的模块安装部署工具——luaRocks”

2)用luaRocks安装luafilesystem;打开终端,在终端执行命令:luarocks install luafilesystem 这样就部署成功了

本文相关代码借鉴Lua-Simple-XML-Parser中的xmlSimple

注:第一次写博客,不足之处请见谅

用lua将xml文件转成lua文件配置相关推荐

  1. .proto 文件转成 lua 文件完整版(Windows 下)

    .proto 文件转成 .lua 文件完整版(Windows 下) 版权声明:本文为博主原创文章,转载请注明CSDN博客源地址!共同学习,一起进步~ https://blog.csdn.net/qq_ ...

  2. 将IphotoDraw标注好的xml文件转成txt文件(三)

    接上一篇来说,将真实的样本过一遍baseline模型后得到最初版的boundingbox信息的txt文件,又将这些txt文件转成xml文件进行纠正,纠正后使用IphotoDraw导出的还是xml文件, ...

  3. C#.NET如何将cs文件编译成dll文件 exe文件 如何调用dll文件

    比如我要把TestDLL.cs文件编译成dll文件,则在命令提示符下,输入下面的命令,生成的文件为TestDLL.dll csc /target:library TestDLL.cs 注意前提是你安装 ...

  4. Java使用aspse实现Excel文件转换成PDF文件

    使用Java代码把Excel文件转换成PDF文件 需要引用aspose包,引入操作我写了一个博客,地址如下 https://blog.csdn.net/weixin_46713508/article/ ...

  5. aspx文件编译成DLL文件的原理

    前言 Asp.net不是asp的简单升级,而是微软.Net计划中的一个重要组成部分,它依托.Net的多语言与强大的类库支持,引进了服务端HTML控件与WEB控件,自动处理控件的客户端与服务端的 交互, ...

  6. 【转载】把aspx文件编译成DLL文件-.NET教程,Asp.Net开发

    前言 asp.net不是asp的简单升级,而是微软.net计划中的一个重要组成部分,它依托.net的多语言与强大的类库支持,引进了服务端html控件与web控件,自动处理控件的客户端与服务端的 交互, ...

  7. Java使用aspose把PDF文件转换成PNG文件,以及把PDF文件水印转换成PNG格式

    Java代码把PDF文件转换成PNG文件 需要引用aspose包,引入操作我写了一个博客,地址如下 https://blog.csdn.net/weixin_46713508/article/deta ...

  8. python将txt转换为csv_Python Pandas 三行代码将 txt 文件转换成 csv 文件

    今天需要处理几个比较大的 txt 文件,每个文件都在 2GB 以上,直接用 Excel 将其转换成 csv 文件显然是不太可行的,于是用 Python 中的数据处理神器 Pandas,三行代码就能搞定 ...

  9. bat脚本中获取上级目录_使用Python写一个可以监控Tomcat 运行的脚本,并且把.py文件转换成.exe文件...

    使用Python写一个可以监控Tomcat 运行的脚本,并且把.py文件转换成.exe文件 文章来源与博主本人的CSDN博客,博客地址:https://blog.csdn.net/weixin_435 ...

  10. java虚拟机编译文件,理解Java虚拟机(1)之一个.java文件编译成.class文件发生了什么...

    理解Java虚拟机(1)之一个.java文件编译成.class文件发生了什么 最近在看<深入理解Java虚拟机>弄明白了很多java的底层知识,决定分几部分总结下,从.java文件编译,到 ...

最新文章

  1. ant自动打包多个android项目为apk
  2. mapreduce v1.0学习笔记
  3. mac php 连接mysql数据库_Mac环境下php操作mysql数据库的方法分享_PHP教程
  4. boost 递归锁_c++/boost互斥量与锁
  5. Microsoft .Net Remoting系列专题之一:.Net Remoting基础篇
  6. 为企业量身定制IT资产管理解决方案(一)
  7. JVM内存模型及垃圾回收机制
  8. y105 usb转rs232驱动
  9. Jackson的JSON——JsonUtils工具类
  10. x的x分之一次方极限x趋于0_x分之e的x次方减一的极限
  11. nanopore测序技术专题(四):纳米孔测序原理
  12. linux系统文件颜色含义
  13. 附加支付和统筹支付_医保附加支付是什么意思?
  14. Debian服务器更改时区为中国
  15. 使用PowerShell替代WinDbg在高分辨率笔记本下调试、排错
  16. 【Centos】sshd 无法启动(解决问题篇,附问题排查思路和解决方法)
  17. Google 新系统 Fuchsia 概览和浅析
  18. SEO一场智慧心理之战
  19. 年薪50万的程序员_毕业之后,这些年薪50万+的90后程序员经历了什么?-阿里云开发者社区...
  20. 脱离取源设备的IPTV宽带机房搭建心得(私网汇聚、内网直播源、单播组播模式混合使用、光猫机顶盒的破解、超级路由的组播转发)

热门文章

  1. 【C语言 strlen函数的实现】
  2. Java 比较两个日期的先后
  3. 深度学习技巧应用20-六大学习率调优方案的应用,并根据实际情况选出最优策略
  4. 【转】学习程序设计的“捷径”——抓大放小,要事为先
  5. 前端切图神器avocode
  6. Linux下TInbsp;omap芯片nbsp;MUX…
  7. Linux TI omap芯片 pinmux分析(以AM335X为例)
  8. 改行迷茫不知道做什么该怎么办?
  9. 小王学JAVA 1.2计算机基本知识
  10. 关于飞鸽FlyGo 学习与成长