Import an XML file

In this example we see how to import an xml file and write data within the database using datarow objects to make the operation easier. Specifically, we will create a small importer of items. The script is an action to be associated directly with the program.

Script Group

Program

Event

Program action


document = program.loadxmldocument()

if document == nil then

do return end

end

First we create a document object that will contain the whole xml file. If you don't enter rhe path between the brackets, the program will show the file selection screen. This operation varies according to the type of operating system because everyone has their own file manager rules.

headitems = document.getelementbyname("Items")

if headitems == nil then

program.showerror("Error in xml (Items) .Unable to continue!")

do return end

end

We extrapolate the first node of the xml file. Of course we need to know what the various nodes are called and if a node that does not exist is requested, the program will return null and exit.

items= headitems.getelementbyname("List")

We extrapolate the sub node containing all the items.

for i,row in pairs(items) do

code= row.getelementbyname("Code").getvalue()

titems= database.getsql("SELECT * FROM items WHERE code='" .. code .. "'")

if titems.countrows() ~= 0 then

rowitem = titems.getrows()[1]

else

rowitem= database.newdatarow("items")

end

rowitem.setvalue("description",row.getelementbyname("Description").getvalue())

rowitem.setvalue("price",tonumber(row.getelementbyname("Price").getvalue()))

if rowitem.save() == false then

program.showerror(errorn.errormessage)

do return end

end

end


We turn all the items and, through the code, we check whether the latter is already present in the database or not. If not, let's create a new row.

As a last step we recover the values we want from the xml file and save the row.