XMLParser example

Discuss about plugins that don't have a dedicated forum
Post Reply
User avatar
mrupp
Posts: 113
Joined: Sun Jan 31, 2021 7:44 pm
Location: Switzerland
Contact:

XMLParser example

Post by mrupp »

Hi
I was struggling for a bit to get the XMLParser working, mainly because there are none of the excellent docs by Andreas but only the one from LuaExpat. Now, I FINALLY got the first example of these docs working and I thought I'd share the info to help others.

Original example from the LuaExpat docs:

Code: Select all

require"lxp"

local count = 0
callbacks = {
    StartElement = function (parser, name)
        io.write("+ ", string.rep(" ", count), name, "\n")
        count = count + 1
    end,
    EndElement = function (parser, name)
        count = count - 1
        io.write("- ", string.rep(" ", count), name, "\n")
    end
}

p = lxp.new(callbacks)

for l in io.lines() do  -- iterate lines
    p:parse(l)          -- parses the line
    p:parse("\n")       -- parses the end of line
end
p:parse()               -- finishes the document
p:close()               -- closes the parser
Translated to Hollywood code:

Code: Select all

@REQUIRE "xmlparser"

Function p_test(xml$)
  Local count = 0
  Local callbacks = {
      StartElement = Function (parser, name)
          DebugPrint("+ ", RepeatStr(" ", count), name, "\n")
          count = count + 1
      EndFunction,
      EndElement = Function (parser, name)
          count = count - 1
          DebugPrint("- ", RepeatStr(" ", count), name, "\n")
      EndFunction
  }
  
  Local p = xmlparser.new(callbacks)

  Local table = SplitStr(xml$, "\n")
  For i, l In IPairs(table)  ; iterate lines
      p:parse(l)             ; parses the line
      p:parse("\n")          ; parses the end of line
  Next
  p:parse()                  ; finishes the document
  p:close()                  ; closes the parser
EndFunction
Usage:

Code: Select all

Local xml$ = [[
<elem1>
  text
<elem2/>
  more text
</elem1>
]]

p_test(xml$)
With this it should be easy to translate the other examples as well.

Cheers,
Michael

Post Reply