XML Tutorial/it

From Lazarus wiki
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) magyar (hu) Bahasa Indonesia (id) italiano (it) 日本語 (ja) 한국어 (ko) português (pt) русский (ru) 中文(中国大陆)‎ (zh_CN)

Introduzione

L'Extensible Markup Language è un linguaggio raccomandato dal W3C creato per l'interscambio di informazioni tra sistemi differenti. Si tratta di un sistema di memorizzazione di informazioni basato su file di testo. Linguaggi moderni di interscambio di dati come XHTML, così come la maggior parte delle tecnologie WebService, sono basati su XML.

Al momento esistono una serie di unit che forniscono supporto per XML su Free Pascal. Queste unit sono chiamate "XMLRead", "XMLWrite" e "DOM" e sono parte della Free Component Library (FCL) del Free Pascal Compiler. La FCL si trova già nei percorsi di ricerca di default per il compilatore in Lazarus, così bisogna soltanto aggiungere queste unit alla clausola uses per avere il supporto di XML. La FCL al momento (Ottobre / 2005) non è documentata, quindi questo breve tutorial introdurrà XML tramite l'utilizzo di queste unit.

XML DOM (Document Object Model) sono una serie di oggetti standardizzati che forniscono un'interfaccia simile per l'utilizzo di XML con differenti linguaggi e su differenti sistemi. Lo standard specifica soltanto i metodi, le proprietà e altre parti dell'interfaccia dell'oggetto, lasciando l'implementazione libera per i diversi linguaggi. La FCL al momento offre pieno supporto per XML DOM 1.0.

Esempi

Di seguito c'è una lista di esempi di manipolazione dati tramite XML di complessità crescente.

Leggere un nodo di testo

Per Programmatori Delphi: Notare che quando si lavora con TXMLDocument, il testo all'interno di un Node viene considerato come un TEXT Node separato. Quindi si deve accedere al valore del testo del nodo come se si trattasse di un nodo separato. In alternativa, è possibile utilizzare la proprietà TextContent per ottenere il contenuto di tutti i nodi di testo al di sotto del nodo specificato, concatenati assieme.

La procedure ReadXMLFile crea sempre un nuovo TXMLDocument, quindi non c'è bisogno di crearlo prima. In ogni caso, assicuratevi di distruggere il documento tramite una chiamata a Free quando avete terminato.

Per esempio, consideriamo il seguente XML:

<xml>

<?xml version="1.0"?>
<request>
  <request_type>PUT_FILE</request_type>
  <username>123</username>
  <password>abc</password>
</request>

</xml>

Il seguente codice di esempio mostra sia il modo corretto che quello non corretto di ottenere il valore del testo del nodo:

<delphi>

var
 PassNode: TDOMNode;
 Doc:      TXMLDocument;
begin
 // Read in xml file from disk
 ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
 // Retrieve the "password" node
 PassNode := Doc.DocumentElement.FindNode('password');
 // Write out value of the selected node
 WriteLn(PassNode.NodeValue); // will be blank
 // The text of the node is actually a separate child node
 WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
 // alternatively
 WriteLn(PassNode.TextContent);
 // finally, free the document
 Doc.Free;

end; </delphi>

Stampare i nomi dei nodi

Una nota veloce sulla navigazione di un albero DOM: quando c'è bisogno di accedere i nodi in sequenza, è preferibile utilizzare le proprietà FirstChild e NextSibling (per scorrerlo in avanti), o LastChild e PreviousSibling (per scorrerlo indietro). Per un accesso random è possibile utilizzare i metodi ChildNodes o GetElementsByTagName, ma questi creeranno un oggetto TDOMNodeList che alla fine deve essere rilasciato. Questo comportamento differisce da altre implementazioni di DOM come MSXML, perché l'implementazione di FCL è basata sugli oggetti, non sulle interfacce.

Il seguente esempio mostra come stampare i nomi dei nodi in un TMemo posizionato su un form.

Qui sotto c'è il file XML chiamato 'C:\Programas\teste.xml':

<xml>

<?xml version="1.0"?>
<images directory="mydir">
 <imageNode URL="graphic.jpg" title="">
   <Peca DestinoX="0" DestinoY="0">Pecacastelo.jpg1.swf</Peca>
   <Peca DestinoX="0" DestinoY="86">Pecacastelo.jpg2.swf</Peca>
 </imageNode>
</images>

</xml>

E qui il codice Pascal per eseguire il compito:

<delphi>

var
  Documento: TXMLDocument;
  Child: TDOMNode;
  j: Integer;
begin
  ReadXMLFile(Documento, 'C:\Programas\teste.xml');
  Memo.Lines.Clear;
  // using FirstChild and NextSibling properties
  Child := Documento.DocumentElement.FirstChild;
  while Assigned(Child) do
  begin
    Memo.Lines.Add(Child.NodeName + ' ' + Child.Attributes.Item[0].NodeValue);
    // using ChildNodes method
    with Child.ChildNodes do
    try
      for j := 0 to (Count - 1) do
        Memo.Lines.Add(Item[j].NodeName + ' ' + Item[j].FirstChild.NodeValue);
    finally
      Free;
    end;
    Child := Child.NextSibling;
  end;
  Documento.Free;
end;

</delphi>

Questo stamperà:

imageNode graphic.jpg
Peca Pecacastelo.jpg1.swf
Peca Pecacastelo.jpg1.swf

Popolare un TreeView tramite XML

Un utilizzo comune dei files XML è quello di eseguire un parsing su di essi e mostrare il loro contenuto in una struttura ad albero. E' possibile trovare il componente TTreeView nella linguetta "Common Controls" in Lazarus.

La funzione qui in basso prenderà un documento XML precedentemente caricato da file o generato via codice e popolerà un TreeView con il suo contenuto. La caption di ogni nodo sarà il contenuto del primo attributo di ogni nodo.

<delphi> procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument); var

 iNode: TDOMNode;
 procedure ProcessNode(Node: TDOMNode; TreeNode: TTreeNode);
 var
   cNode: TDOMNode;
 begin
   if Node = nil then Exit; // Stops if reached a leaf
   
   // Adds a node to the tree
   TreeNode := tree.Items.AddChild(TreeNode, Node.Attributes[0].NodeValue);
   // Goes to the child node
   cNode := Node.FirstChild;
   // Processes all child nodes
   while cNode <> nil do
   begin
     ProcessNode(cNode, TreeNode);
     cNode := cNode.NextSibling;
   end;
 end;
   

begin

 iNode := XMLDoc.DocumentElement.FirstChild;
 while iNode <> nil do
 begin
   ProcessNode(iNode, nil); // Recursive
   iNode := iNode.NextSibling;
 end;

end; </delphi>

Modificare un documento XML

The first thing to remember is that TDOMDocument is the "handle" to the DOM. You can get an instance of this class by creating one or by loading a XML document.

Nodes on the other hand cannot be created like a normal object. You *must* use the methods provided by TDOMDocument to create them, and latter use other methods to put them on the correct place on the tree. This is because nodes must be "owned" by a specific document on DOM.

Below are some common methods from TDOMDocument:

<delphi>

  function CreateElement(const tagName: DOMString): TDOMElement; virtual;
  function CreateTextNode(const data: DOMString): TDOMText;
  function CreateCDATASection(const data: DOMString): TDOMCDATASection;
    virtual;
  function CreateAttribute(const name: DOMString): TDOMAttr; virtual;

</delphi>

And here an example method that will locate the selected item on a TTreeView and then insert a child node to the XML document it represents. The TreeView must be previously filled with the contents of a XML file using the XML2Tree function.

<delphi> procedure TForm1.actAddChildNode(Sender: TObject); var

 position: Integer;
 NovoNo: TDomNode;

begin

 {*******************************************************************
 *  Detects the selected element
 *******************************************************************}
 if TreeView1.Selected = nil then Exit;
 if TreeView1.Selected.Level = 0 then
 begin
   position := TreeView1.Selected.Index;
   NovoNo := XMLDoc.CreateElement('item');
   TDOMElement(NovoNo).SetAttribute('nome', 'Item');
   TDOMElement(NovoNo).SetAttribute('arquivo', 'Arquivo');
   with XMLDoc.DocumentElement.ChildNodes do
   begin
     Item[position].AppendChild(NovoNo);
     Free;
   end;
   {*******************************************************************
   *  Updates the TreeView
   *******************************************************************}
   TreeView1.Items.Clear;
   XML2Tree(TreeView1, XMLDoc);
 end
 else if TreeView1.Selected.Level >= 1 then
 begin
   {*******************************************************************
   *  This function only works on the first level of the tree,
   *  but can easely modifyed to work for any number of levels
   *******************************************************************}
 end;

end; </delphi>

Creare un TXMLDocument da una stringa

Given al XML file in MyXmlString, the following code will create it's DOM:

<delphi> Var

 S : TStringStream;
 XML : TXMLDocument;

begin

 S:= TStringStream.Create(MyXMLString);
 Try
   S.Position:=0;
   XML:=Nil;
   ReadXMLFile(XML,S); // Complete XML document
   // Alternatively:
   ReadXMLFragment(AParentNode,S); // Read only XML fragment.
 Finally
   S.Free;
 end;

end; </delphi>

Validare un documento

Since March 2007, DTD validation facility has been added to the FCL XML parser. Validation is checking that logical structure of the document conforms to the predefined rules, called Document Type Definition (DTD).

Here is an example of XML document with a DTD:

<xml>

 <?xml version='1.0'?>
 <!DOCTYPE root [
 <!ELEMENT root (child)+ >
 <!ELEMENT child (#PCDATA)>
 ]>
 <root>
   <child>This is a first child.</child>
   <child>And this is the second one.</child>
 </root>

</xml>

This DTD specifies that 'root' element must have one or more 'child' elements, and that 'child' elements may have only character data inside. If parser detects any violations from these rules, it will report them.

Loading such document is slightly more complicated. Let's assume we have XML data in a TStream object:

<delphi> procedure TMyObject.DOMFromStream(AStream: TStream); var

 Parser: TDOMParser;
 Src: TXMLInputSource;
 TheDoc: TXMLDocument;

begin

 // create a parser object
 Parser := TDOMParser.Create;
 // and the input source
 Src := TXMLInputSource.Create(AStream);
 // we want validation
 Parser.Options.Validate := True;
 // assign a error handler which will receive notifications
 Parser.OnError := @ErrorHandler;
 // now do the job
 Parser.Parse(Src, TheDoc);
 // ...and cleanup
 Src.Free;
 Parser.Free;

end;

procedure TMyObject.ErrorHandler(E: EXMLReadError); begin

 if E.Severity = esError then  // we are interested in validation errors only
   writeln(E.Message);

end; </delphi>

Generare un file XML

Below is the complete code to write in a XML file. (This was taken from a tutorial in DeveLazarus blog ) Please, remember DOM and XMLWrite libs in uses clause

<delphi> unit Unit1;

{$mode objfpc}{$H+}

interface

uses

 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,
 DOM, XMLWrite;

type

 { TForm1 }
 TForm1 = class(TForm)
   Button1: TButton;
   Label1: TLabel;
   Label2: TLabel;
   procedure Button1Click(Sender: TObject);
 private
   { private declarations }
 public
   { public declarations }
 end;
 

var

 Form1: TForm1;
 

implementation

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject); var

 xdoc: TXMLDocument;                                  // variable to document
 RootNode, parentNode, nofilho: TDOMNode;                    // variable to nodes

begin

 //create a document
 xdoc := TXMLDocument.create;
 //create a root node
 RootNode := xdoc.CreateElement('register');
 Xdoc.Appendchild(RootNode);                           // save root node
 //create a parent node
 RootNode:= xdoc.DocumentElement;
 parentNode := xdoc.CreateElement('usuario');
 TDOMElement(parentNode).SetAttribute('id', '001');       // create atributes to parent node
 RootNode.Appendchild(parentNode);                          // save parent node
 //create a child node
 parentNode := xdoc.CreateElement('nome');                // create a child node
 //TDOMElement(parentNode).SetAttribute('sexo', 'M');     // create atributes
 nofilho := xdoc.CreateTextNode('Fernando');         // insert a value to node
 parentNode.Appendchild(nofilho);                         // save node
 RootNode.ChildNodes.Item[0].AppendChild(parentNode);       // insert child node in respective parent node
 //create a child node
 parentNode := xdoc.CreateElement('idade');               // create a child node
 //TDOMElement(parentNode).SetAttribute('ano', '1976');   // create atributes
 nofilho := xdoc.CreateTextNode('32');               // insert a value to node
 parentNode.Appendchild(nofilho);                         // save node
 .ChildNodes.Item[0].AppendChild(parentNode);       // insert a childnode in respective parent node
 writeXMLFile(xDoc,'teste.xml');                     // write to XML
 Xdoc.free;                                          // free memory

end;

initialization

 {$I unit1.lrs}

end. </delphi>

The result will be the XML file below: <xml> <?xml version="1.0"?> <register>

 <usuario id="001">
   <nome>Fernando</nome>
   <idade>32</idade>
 </usuario>

</register> </xml>

--Fernandosinesio 22:28, 24 April 2008 (CEST)fernandosinesio@gmail.com

Codifica

Starting from SVN revision 12582, XML reader is able to process data in any encoding by using external decoders. See XML_Decoders for more details.

According to the XML standard, the encoding attribute in the first line of the XML is optional in case the actual encoding is UTF-8 or UTF-16 (which is detected by presence of the BOM). As of version 0.9.26 of Lazarus, there is an encoding property in a TXMLDocument, but it is ignored. writeXMLFile always uses UTF-8 and doesn´t generate an encoding attribute in first line of the XML file.

Link Esterni


Multithreaded Application Tutorial