miércoles, 27 de mayo de 2015

Leer XML de la web y grabar en base de datos

Para algunos trabajar con archivos XML puede ser confuso y engorroso, sin embargo Xojo nos facilita mucho el trabajo con su clase XMLDocument.

He preparado un pequeño paso a paso con un ejemplo que viene con Xojo, la versión que trabajo es la 2015r21 pero funciona con versiones anteriores.
  1. En la ventana "Project Chooser" clic en Examples, Communications/Internet/HTTP Example.xojo_binary_project.
  2. Cambiar la propiedad Super de EdidFieldPlus a TextArea.
  3. Crear un Botón con el caption toDB y en evento action adicionar el código.
  4. Correr en proyecto.
  5. Cambiar la URL a "http://www.w3schools.com/xml/cd_catalog.xml" oprimir "Go".
  6. Oprmir "toDB" y revisar la baseDatos "FromXML.sqlite" del escritorio.

Código para toDB.Action:

  Dim f As FolderItem= SpecialFolder.Desktop.Child("FromXML.sqlite")
  
  Dim db As New SQLiteDatabase
  db.DatabaseFile= f
  
  If f= Nil Or Not f.Exists Then
    If db.CreateDatabaseFile Then
      Dim sql As String= "CREATE TABLE cd_catalog (title TEXT, artist TEXT, year INT);"
      db.SQLExecute(sql)
      If db.Error Then
        MsgBox "DB Error: " + db.ErrorMessage
        Return
      End If
    Else
      MsgBox "The database couldn't be created. Error: " + db.ErrorMessage
      Return
    End If
  Else
    If Not db.Connect Then
      MsgBox "The database couldn't be opened. Error: " + db.ErrorMessage
      Return
    End If
  End If
  
  Dim xml As New XmlDocument(BodyField.Text)
  
  Dim ps As SQLitePreparedStatement= db.Prepare("INSERT INTO cd_catalog (title, artist, year) VALUES (?, ?, ?)")
  ps.BindType(0, SQLitePreparedStatement.SQLITE_TEXT)
  ps.BindType(1, SQLitePreparedStatement.SQLITE_TEXT)
  ps.BindType(2, SQLitePreparedStatement.SQLITE_INTEGER)
  
  db.SQLExecute("BEGIN TRANSACTION")
  
  For i As Integer= 0 To xml.DocumentElement.ChildCount- 1
    Dim sTitle, sArtist As String
    Dim iYear As Integer
    For j As Integer= 0 To xml.DocumentElement.Child(i).ChildCount- 1
      Dim node As XmlNode= xml.DocumentElement.Child(i).Child(j)
      Select Case node.Name.Uppercase
      Case "TITLE"
        sTitle= node.Child(0).Value
      Case "ARTIST"
        sArtist= node.Child(0).Value
      Case "YEAR"
        iYear= Val(node.Child(0).Value)
      End Select
    Next
    ps.SQLExecute(sTitle, sArtist, iYear)
  Next
  
  db.Commit


Puede ver video aquí.

Espero les sirva, chao, chao.

No hay comentarios:

Publicar un comentario