寫在前面,這是一個最好理解的解析方法,當然也是被棄用的一種方法,哈哈哈,這個是我最早的解決方法,毫無疑問的在后面被大神的神技折服了。
什么原理?
核心是字符串的操作,具體編寫了兩個方法,字符串匹配以及字符串分組。主要用到的方法有:
●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取值即可。