LuaXML parses XML with multiple tags with the same name

I am trying to parse data from XML files, for example

<level> <bg>details1</bg> <bg>details2</bg> </level> 

With xml.find (bg) I can only get details 1. This is because xml.find returns the first (sub) table that matches the search condition or nil.

If I want to read both bg out. How can I achieve this in LuaXML? Or please check out other Lua XML libraries.

Addons My real scenario is like this

 <a> <b> <level> <bg>details1</bg> </level> <level> <bg>details2</bg> </level> </b> </a> 

I know that I need to get the whole object b and use xml.tag to read the level. But my attempts fail. Could you help me in this code?


I finally got my decision based on a proposal from Mike Corcoran.

 require 'luaxml' local text = [[ <a> <bcde> <level> <bg>details1</bg> </level> <level> <bg>details2</bg> </level> </bcde> </a> ]] local txml = xml.eval(text) for _, node in pairs(txml:find("bcde")) do if node.TAG ~= nil then if node[node.TAG] == "level" then local bg = node:find("bg") if bg ~= nil then for i=1, #bg do print( bg[i]) end end end end end 

Too many layers and it seems slow .. Any suggestion to increase efficiency?

+4
source share
2 answers

Just iterate over all the children of the level tag (if there is no other information there, you do not inform us about it, you need to filter it)

 require 'luaxml' local text = [[ <level> <bg>details1</bg> <bg>details2</bg> </level> ]] local VALUE = 1 local txml = xml.eval(text) for _, node in pairs(txml:find("level")) do if node.TAG ~= nil then print(node[VALUE]) end end 

and if you need to filter everything except the <bg> tags, you can just change this loop a bit:

 for _, node in pairs(txml:find("level")) do if node.TAG ~= nil then if node[node.TAG] == "bg" then print(node[VALUE]) end end end 
+2
source

After calling xml.load you will get a table representing the just downloaded xml file. You can go to a specific node by accessing the corresponding numeric index in the table:

 require 'luaxml' local level = xml.load('level.xml') -- level[1] == <bg>details1</bg> -- level[2] == <bg>details2</bg> for i = 1, #level do print(level[i]) end 

Edit: From the edited question, here is one way to output data from an XML file:

 require 'luaxml' local xmlroot = xml.load('your.xml') local b = xmlroot:find 'b' for level = 1, #b do print(b[level][1][1]) end 

If you have control over the XML format, you can modify it a bit to make parsing easier to understand:

 <a> <b> <level bg="details1"> </level> <level bg="details2"> </level> </b> </a> 

With this change, bg becomes the level node attribute. This reduces one level of indirection. To access the bg attribute, simply use the lua operator . with bg as the key. Then the parsing cycle can be changed to:

 for level = 1, #b do print(b[level].bg) end 
+3
source

Source: https://habr.com/ru/post/1491956/


All Articles