|
Programación: Cómo crear, acceder y manipular ficheros XML con Delphi
Os explicamos con código de ejemplo cómo crear, acceder, mostrar y modificar ficheros XML (Extensible Markup Language ó lenguaje de marcas extensible) con Delphi. Utilizaremos el componente ClientDataset. XML es un metalenguaje extensible de etiquetas desarrollado por W3C (World Wide Web Consortium). Es una simplificación y adaptación del SGML (Standard Generalized Markup Language) y permite definir la gramática de lenguajes específicos.XML es una manera de definir lenguajes para diferentes necesidades: XHTML, SVG, MathML, etc. XML es un estándar para el intercambio de información estructurada entre diferentes plataformas: bases de datos, editores de texto, hojas de cálculo, etc. Un ejemplo de uso de XML es el usado en el formato KML para Google Earth. A continuación os mostramos cómo acceder a un fichero XML con Delphi y poder tratarlo (modificarlo) desde una aplicación realizada en este lenguaje. Abriremos Delphi, pulsaremos en "File" - "New" - "Application":
Accederemos a la pestaña "Data Access" de la paleta de componentes (Component Palette) y seleccionaremos el componente ClientDataset: Se trata de un componente que incluye Delphi 6 para tratamiento y acceso a ficheros XML (entre otros formatos). Este componente tiene las siguientes propiedades: Active, Aggregates, AggregatesActive, AutoCalcFields, CommandText, ConnetionBroker, Constraints, DataSetField, DisableStringTrim, FetchOnDemand, FieldDefs, FileName, Filter, Filtered, FilterOptions, IndexDefs, IndexFieldNames, IndexName, MasterFields, MasterSource, Name, ObjectView, PacketRecords, Params, ProviderName, ReadOnly, RemoteServer, StoreDefs, Tag:
Las que utilizaremos para el ejemplo:
Añadiremos varios componentes al formulario de nuestra aplicación: TPageControl, TGroupBox, TEdit, TComboBox, TBitBtn, TStatusBar, etc: Los componentes TComboBox, en su propiedad "Items" tendrán:
A continuación añadiremos el código fuente al botón "Crear fichero XML", será el siguiente: procedure TformMenuPrincipal.bCrearXMLClick(Sender: TObject); var crearXML : Boolean; begin if txtFicheroXML.Text <> '' then begin if FileExists(txtFicheroXML.Text) then begin crearXML := MessageDlg('El fichero XML seleccionado ' + 'ya existe ¿desea reemplazarlo?', mtConfirmation, [mbyes, mbno], 0) = mryes; end else crearXML := true; if crearXML then begin if (txtCampo1.Text = '') and (txtCampo2.Text = '') and (txtCampo3.Text = '') and (txtCampo4.Text = '') and (txtCampo5.Text = '') then begin crearXML := false; MessageDlg('Debe indicar el nombre de algún campo.', mtInformation, [mbok], 0); txtCampo1.SetFocus; end; end; if crearXML then begin tXML.Close; tXML.FieldDefs.Clear; if txtCampo1.Text <> '' then begin if txtTamano1.Text = '' then txtTamano1.Text := '0'; crearCampoXML (txtCampo1.Text, txtTipoDato1.Text, StrToInt(txtTamano1.Text)); end; if txtCampo2.Text <> '' then begin if txtTamano2.Text = '' then txtTamano2.Text := '0'; crearCampoXML (txtCampo2.Text, txtTipoDato2.Text, StrToInt(txtTamano2.Text)); end; if txtCampo3.Text <> '' then begin if txtTamano3.Text = '' then txtTamano3.Text := '0'; crearCampoXML (txtCampo3.Text, txtTipoDato3.Text, StrToInt(txtTamano3.Text)); end; if txtCampo4.Text <> '' then begin if txtTamano4.Text = '' then txtTamano4.Text := '0'; crearCampoXML (txtCampo4.Text, txtTipoDato4.Text, StrToInt(txtTamano4.Text)); end; if txtCampo5.Text <> '' then begin if txtTamano5.Text = '' then txtTamano5.Text := '0'; crearCampoXML (txtCampo5.Text, txtTipoDato5.Text, StrToInt(txtTamano5.Text)); end; try tXML.CreateDataSet; tXML.SaveToFile(txtFicheroXML.Text, dfXMLUTF8); tXML.Close; MessageDlg('El fichero XML se ha creado correctamente.', mtInformation, [mbok], 0); except raise end; end; end else MessageDlg('Debe indicar la ubicación y el nombre ' + 'del fichero XML a crear.', mtInformation, [mbok], 0) end; El código de las funciones y procedimientos utilizados por el botón anterior: function obtenerTipoDatos (tipo : string) : TFieldType; begin Result := ftString; if tipo = 'Cadena de texto (String)' then Result := ftString; if tipo = 'Fecha/Hora (DateTime)' then Result := ftDateTime; if tipo = 'Número entero (Integer)' then Result := ftInteger; if tipo = 'Número real (Float)' then Result := ftFloat; if tipo = 'Sí/No (Boolean)' then Result := ftBoolean; if tipo = 'Texto grande (Memo)' then Result := ftMemo; end; procedure TformMenuPrincipal.crearCampoXML (nombre : string; tipoDatosStr : string; tamano : integer); begin tXML.FieldDefs.Add (nombre, obtenerTipoDatos(tipoDatosStr), tamano); end; El código del botón "Seleccionar fichero XML": procedure TformMenuPrincipal.bSelFicheroClick(Sender: TObject); begin if dlGuardar.Execute then txtFicheroXML.Text := dlGuardar.FileName; end;
La parte de "Creación XML" de la aplicación Delphi de ejemplo en ejecución: El resultado de pulsar el botón "Crear fichero XML" será:
y el contenido: Anuncios
Enviado el Martes, 25 marzo a las 01:33:02 por ajpdsoft
|
|