LUA example: Import an XML file

In this example we’ll see how to import an XML file and write the data to the database, using datarow objects to make the job easier. Specifically, we’ll build a small item importer. The script is an action linked directly to the program.

Script Group
Program
Event
Program Action
documento = program.loadxmldocument()

if documento == nil then
   do return end
end

First we create a document object that will hold the whole XML file. If no path is given between the brackets, the program shows the file selection screen. This step varies by operating system, because each one has its own file handling rules.

testaarticoli = documento.getelementbyname("Articoli")

if testaarticoli == nil then
   program.showerror("XML error (Articoli). Unable to continue!")
   do return end
end

We extract the first node of the XML file. Of course, we need to know the names of the nodes; if a node that doesn’t exist is requested, the program returns nil and the script exits.

articoli = testaarticoli.getelementbyname("Elenco")

We extract the child node containing all the items.

for i,riga in pairs(articoli) do

   codice = riga.getelementbyname("Codice").getvalue()
   tarticoli = database.getsql("SELECT * FROM articoli WHERE codice='" .. utility.convap(codice) .. "'")

      if tarticoli.countrows() ~= 0 then
         rigaarticolo = tarticoli.getrows()[1]
      else
         rigaarticolo = database.newdatarow("articoli")
      end
      rigaarticolo.setvalue("descrizione",riga.getelementbyname("Descrizione").getvalue())
   rigaarticolo.setvalue("prezzo",tonumber(riga.getelementbyname("Prezzo").getvalue()))

   if rigaarticolo.save() == false then
      program.showerror(errorn.errormessage)
      do return end
    end

end

We go through all the items and use the code to check whether each one already exists in the database. If it doesn’t, we create a new row.

Finally, we take the values we want from the XML file and save the row.