Persisting DataTable to XML - revisited

Started by spl, October 05, 2024, 08:39:07 AM

Previous topic - Next topic

spl

This works. Not sure if anyone interested or cares.
;WB 2024B Simple typed .Net DataTable
;Stan Littlefield 10/05/2024
;persisted to xml with schema
;suggested you save as [path]\DataTableSchema2XML.wbt can be run 32bit
;===============================================================================================================
gosub udfs
IntControl(73,1,0,0,0)
ObjectClrOption("useany","System.Data")
tablename = "Employees"
file = dirscript():"dt2xml.xml"
if fileexist(file) Then  filedelete(file)
dt = ObjectClrNew("System.Data.DataTable",tablename)

bTrue = ObjectType( "BOOL", -1 )
bFalse = ObjectType( "BOOL", 0 )
oType = ObjectClrNew('System.Type')
ostr = oType.GetType("System.String")
oint = oType.GetType("System.Int32")
odate = oType.GetType("System.Object")
obool = oType.GetType("System.Boolean")

oColumn = ObjectClrNew("System.Data.DataColumn","Name", ostr)
oColumn.AllowDBNull = bTrue     
dt.Columns.Add(oColumn)

oColumn = ObjectClrNew("System.Data.DataColumn","Salary", oint) 
oColumn.AllowDBNull = bTrue     
dt.Columns.Add(oColumn)

oColumn = ObjectClrNew("System.Data.DataColumn","DOB", odate)   
oColumn.AllowDBNull = bTrue 
dt.Columns.Add(oColumn)

oColumn = ObjectClrNew("System.Data.DataColumn","Location", ostr)
oColumn.AllowDBNull = bTrue     
dt.Columns.Add(oColumn)

oColumn = ObjectClrNew("System.Data.DataColumn","Hourly", obool)     
dt.Columns.Add(oColumn)

dt.Rows.Add("Brian", "55000", "04/17/1999","UK",@FALSE)
dt.Rows.Add("Sam", "107000","2009-03-15 09:11:00", "Canada",0)
dt.Rows.Add("Eric","25000","03/05/2007", "USA",@TRUE)
dt.Rows.Add("Joe","39000",0, "USA",@TRUE)

writer = ObjectClrNew("System.IO.StreamWriter",file)
mode = ObjectClrType("System.Data.XmlWriteMode",0)
dt.WriteXml(writer,mode)

writer.Flush()
writer.Close()
writer=0
dt.Clear()
dt=0

if fileexist(file)
   Display(2,"XML Created",file)

   ;use this to view
   f = fileget(file)
   Message("DataTable=>XML",f)

   ;or this [a little more readable]
   ;Run("notepad.exe",file)

else
   Display(2,"Could Not Create",file)
Endif

Exit

:WBERRORHANDLER
dt=0
writer=0
geterror()
Message("Error Encountered",errmsg)
Exit
;===============================================================================================================

:udfs
#DefineSubRoutine geterror()
   wberroradditionalinfo = wberrorarray[6]
   lasterr = wberrorarray[0]
   handlerline = wberrorarray[1]
   textstring = wberrorarray[5]
   linenumber = wberrorarray[8]
   errmsg = "Error: ":lasterr:@LF:textstring:@LF:"Line (":linenumber:")":@LF:wberroradditionalinfo
   Return(errmsg)
#EndSubRoutine

Return
;===============================================================================================================
Stan - formerly stanl [ex-Pundit]