Unity教程合集征服Unity3d

Lua简单解析xml

2017-08-18  本文已影响0人  黒可乐

写在前面,这是一个最好理解的解析方法,当然也是被弃用的一种方法,哈哈哈,这个是我最早的解决方法,毫无疑问的在后面被大神的神技折服了。

什么原理?

核心是字符串的操作,具体编写了两个方法,字符串匹配以及字符串分组。主要用到的方法有:
●string.find("str","str",index)
●string.sub("str",startIndex,endIndex)
●string.match("str","matchStr")

分别实现

分割字符串:

function Split(szFullString, szSeparator)  
    local nFindStartIndex = 1  
    local nSplitIndex = 1  
    local nSplitArray = {}  
    while true do  
       local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)  
       if not nFindLastIndex then  
            nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))  
            break  
       end  
       nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)  
       nFindStartIndex = nFindLastIndex + string.len(szSeparator)  
       nSplitIndex = nSplitIndex + 1  
    end  
    return nSplitArray  
end

字符串匹配:

function GetXMLValue(content, key)
    local value_pattern = "<"..key..">(.*)</"..key..">"
    local value = string.match(content, value_pattern)
    Log("yellow", "content-->",content,"key-->", key, "value-->", value)
    if value then
        return value
    else
        return ""
    end
end

这个方法只会匹配最开始找到的字符串,不会找后面的。

具体使用:

如果是多个同一种数据体的xml,咱们的先使用Split方法把每一个数据体分开,然后使用GetXMLValue挨着取值。

如果是单独数据体,直接使用GetXMLValue取值即可。

上一篇 下一篇

猜你喜欢

热点阅读