Difference between revisions of "XML Tutorial/id"

From Lazarus wiki
Jump to navigationJump to search
(New page: {{XML Tutorial}} == Pengenalan == The Extensible Markup Language is a [http://www.w3.org/ W3C] recommended language created to interchange information between different systems. It is a ...)
 
m (Fixed syntax highlighting)
 
(6 intermediate revisions by 3 users not shown)
Line 3: Line 3:
 
== Pengenalan ==
 
== Pengenalan ==
  
The Extensible Markup Language is a [http://www.w3.org/ W3C] recommended language created to interchange information between different systems. It is a text based way to store information. Modern data interchange languages such as XHTML, as well as most WebServices technologies, are based on XML.
+
Extensible Markup Language adalah bahasa yang direkomendasikan oleh [http://www.w3.org/ W3C] yang dibuat untuk bertukar informasi diantara sistem yang berbeda. Ia adalah cara berbasis teks untuk menyimpan informasi. Bahasa pertukaran data modern seperti misalnya XHTML, juga umumnya teknologi WebServices, berbasiskan pada XML.
  
Currently there is a set of units that provides support for XML on Free Pascal. These units are called "XMLRead", "XMLWrite" and "DOM" and they are part of the Free Component Library (FCL) from the Free Pascal Compiler. The FCL is already on the default search path for the compiler on Lazarus, so you only need to add the units to your uses clause in order to get XML support. The FCL is not documented currently (October / 2005), so this short tutorial aims at introducing XML access using those units.
+
Saat ini ada satu set unit yang menyediakan dukungan untuk XML pada Free Pascal. Unit ini disebut "XMLRead", "XMLWrite" dan "DOM" dan ketiganya adalah bagian dari Free Component Library (FCL) dari Free Pascal Compiler. FCL sudah pada path pencarian standar untuk kompilator pada Lazarus, maka Anda hanya perlu menambahkan unit ke klausul uses Anda untuk mendapatkan dukungan XML. FCL saat ini tidak didokumentasikan (Oktober / 2005), maka ini semacam tutorial yang bertujuan untuk memperkenalkan akses XML menggunakan unit-unit tersebut.
  
The XML DOM (Document Object Model) is a set of standarized objects that provide a similar interface for the use of XML on different languages and systems. The standard only specifies the methods, properties and other interface parts of the object, leaving the implementation free for different languages. The FCL currently supports fully the [http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ XML DOM 1.0].
+
XML DOM (Document Object Model) adalah satu set obyek yang distandarisasi yang menyediakan antarmuka untuk pemakaian XML pada beberapa sistem dan bahasa yang berbeda. Standar hanya menetapkan metode, properti dan bagian antarmuka lain terhadap obyek, membiarkan implementasi bebas untuk bahasa yang berbeda. FCL saat ini mendukung penuh [http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ XML DOM 1.0].
  
 
== Contoh ==
 
== Contoh ==
  
Bellow there is a list of XML data manipulation examples with growing complexity.
+
Di bawah ada daftar contoh manipulasi data XML dengan perkembangan yang kompleks.
  
 
=== Membaca node teks ===
 
=== Membaca node teks ===
  
For Delphi Programmers:
+
Untuk Pemrogram Delphi:
Note that when working with TXMLDocument, the text within a Node is considered a separate TEXT NodeAs a result, you must access a node's text value as a separate node. Alternatively, the '''TextContent''' property may be used to retrieve content of all text nodes beneath the given one, concatenated together.
+
Catatan bahwa saat bekerja dengan TXMLDocument, teks di dalam sebuah Node dianggap sebagai Node TEXT terpisahHasilnya, Anda harus mengakses nilai teks node sebagai node terpisah. Alternatif lain, properti '''TextContent''' dapat dipakai untuk mengambil isi dari semua node teks di bawahnya, digabung bersamaan.
  
The '''ReadXMLFile''' procedure always creates a new '''TXMLDocument''', so you don't have to create it beforehand. However, be sure to destroy the document by calling '''Free''' when you are done.
+
Prosedur '''ReadXMLFile''' selalu membuat '''TXMLDocument''' baru, maka Anda tidak harus membuat sebelumnya. Akan tetapi, pastikan untuk membersihkan dokumen dengan memanggil '''Free''' ketika Anda selesai.
  
For instance, consider the following XML:
+
Sebagai contoh, pertimbangkan XML berikut:
  
<xml>
+
<syntaxhighlight lang="xml">
  <?xml version="1.0" encoding="utf-8"?>
+
  <?xml version="1.0"?>
 
  <request>
 
  <request>
 
   <request_type>PUT_FILE</request_type>
 
   <request_type>PUT_FILE</request_type>
Line 29: Line 29:
 
   <password>abc</password>
 
   <password>abc</password>
 
  </request>
 
  </request>
</xml>
+
</syntaxhighlight>
  
The following code example shows both the correct and the incorrect ways of getting the value of the text node:
+
Contoh kode berikut menampilkan cara yang benar dan salah atas mendapatkan nilai node teks:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
  var
 
  var
 
   PassNode: TDOMNode;
 
   PassNode: TDOMNode;
Line 51: Line 51:
 
   Doc.Free;
 
   Doc.Free;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
 
=== Menampilkan nama node ===
 
=== Menampilkan nama node ===
Line 61: Line 61:
 
Bellow is the XML file called 'C:\Programas\teste.xml':
 
Bellow is the XML file called 'C:\Programas\teste.xml':
  
<xml>
+
<syntaxhighlight lang="xml">
  <?xml version="1.0" encoding="ISO-8859-1"?>
+
  <?xml version="1.0"?>
 
  <images directory="mydir">
 
  <images directory="mydir">
 
   <imageNode URL="graphic.jpg" title="">
 
   <imageNode URL="graphic.jpg" title="">
Line 69: Line 69:
 
   </imageNode>
 
   </imageNode>
 
  </images>
 
  </images>
</xml>
+
</syntaxhighlight>
  
 
And here the Pascal code to execute the task:
 
And here the Pascal code to execute the task:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
  var
 
  var
 
   Documento: TXMLDocument;
 
   Documento: TXMLDocument;
Line 98: Line 98:
 
   Documento.Free;
 
   Documento.Free;
 
  end;
 
  end;
</delphi>
+
</syntaxhighlight>
  
 
This will print:
 
This will print:
Line 114: Line 114:
 
The function below will take a XML document previously loaded from a file or generated on code, and will populate a TreeView with it´s contents. The caption of each node will be the content of the first attribute of each node.
 
The function below will take a XML document previously loaded from a file or generated on code, and will populate a TreeView with it´s contents. The caption of each node will be the content of the first attribute of each node.
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
 
procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
 
var
 
var
Line 147: Line 147:
 
   end;
 
   end;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
 
=== Memodifikasi dokumen XML ===
 
=== Memodifikasi dokumen XML ===
Line 157: Line 157:
 
Below are some common methods from TDOMDocument:
 
Below are some common methods from TDOMDocument:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
   function CreateElement(const tagName: DOMString): TDOMElement; virtual;
 
   function CreateElement(const tagName: DOMString): TDOMElement; virtual;
 
   function CreateTextNode(const data: DOMString): TDOMText;
 
   function CreateTextNode(const data: DOMString): TDOMText;
Line 163: Line 163:
 
     virtual;
 
     virtual;
 
   function CreateAttribute(const name: DOMString): TDOMAttr; virtual;
 
   function CreateAttribute(const name: DOMString): TDOMAttr; virtual;
</delphi>
+
</syntaxhighlight>
  
 
And here an example method that will located 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 [[Networking#Populating a TreeView with XML|XML2Tree function]].
 
And here an example method that will located 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 [[Networking#Populating a TreeView with XML|XML2Tree function]].
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.actAddChildNode(Sender: TObject);
 
procedure TForm1.actAddChildNode(Sender: TObject);
 
var
 
var
Line 205: Line 205:
 
   end;
 
   end;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
 
=== Membuat TXMLDocument dari string ===
 
=== Membuat TXMLDocument dari string ===
Line 211: Line 211:
 
Given al XML file in MyXmlString, the following code will create it's DOM:
 
Given al XML file in MyXmlString, the following code will create it's DOM:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
Var
 
Var
 
   S : TStringStream;
 
   S : TStringStream;
Line 228: Line 228:
 
   end;
 
   end;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
 
=== Memvalidasi dokumen ===
 
=== Memvalidasi dokumen ===
Line 236: Line 236:
 
Here is an example of XML document with a DTD:
 
Here is an example of XML document with a DTD:
  
<xml>
+
<syntaxhighlight lang="xml">
   <?xml version='1.0' encoding='utf-8'?>
+
   <?xml version='1.0'?>
 
   <!DOCTYPE root [
 
   <!DOCTYPE root [
 
   <!ELEMENT root (child)+ >
 
   <!ELEMENT root (child)+ >
Line 246: Line 246:
 
     <child>And this is the second one.</child>
 
     <child>And this is the second one.</child>
 
   </root>
 
   </root>
</xml>
+
</syntaxhighlight>
  
 
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.
 
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.
Line 252: Line 252:
 
Loading such document is slightly more complicated. Let's assume we have XML data in a TStream object:
 
Loading such document is slightly more complicated. Let's assume we have XML data in a TStream object:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
procedure TMyObject.DOMFromStream(AStream: TStream);
 
procedure TMyObject.DOMFromStream(AStream: TStream);
 
var
 
var
Line 279: Line 279:
 
     writeln(E.Message);
 
     writeln(E.Message);
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
 
== Link Eksternal ==
 
== Link Eksternal ==

Latest revision as of 03:44, 2 March 2020

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)

Pengenalan

Extensible Markup Language adalah bahasa yang direkomendasikan oleh W3C yang dibuat untuk bertukar informasi diantara sistem yang berbeda. Ia adalah cara berbasis teks untuk menyimpan informasi. Bahasa pertukaran data modern seperti misalnya XHTML, juga umumnya teknologi WebServices, berbasiskan pada XML.

Saat ini ada satu set unit yang menyediakan dukungan untuk XML pada Free Pascal. Unit ini disebut "XMLRead", "XMLWrite" dan "DOM" dan ketiganya adalah bagian dari Free Component Library (FCL) dari Free Pascal Compiler. FCL sudah pada path pencarian standar untuk kompilator pada Lazarus, maka Anda hanya perlu menambahkan unit ke klausul uses Anda untuk mendapatkan dukungan XML. FCL saat ini tidak didokumentasikan (Oktober / 2005), maka ini semacam tutorial yang bertujuan untuk memperkenalkan akses XML menggunakan unit-unit tersebut.

XML DOM (Document Object Model) adalah satu set obyek yang distandarisasi yang menyediakan antarmuka untuk pemakaian XML pada beberapa sistem dan bahasa yang berbeda. Standar hanya menetapkan metode, properti dan bagian antarmuka lain terhadap obyek, membiarkan implementasi bebas untuk bahasa yang berbeda. FCL saat ini mendukung penuh XML DOM 1.0.

Contoh

Di bawah ada daftar contoh manipulasi data XML dengan perkembangan yang kompleks.

Membaca node teks

Untuk Pemrogram Delphi: Catatan bahwa saat bekerja dengan TXMLDocument, teks di dalam sebuah Node dianggap sebagai Node TEXT terpisah. Hasilnya, Anda harus mengakses nilai teks node sebagai node terpisah. Alternatif lain, properti TextContent dapat dipakai untuk mengambil isi dari semua node teks di bawahnya, digabung bersamaan.

Prosedur ReadXMLFile selalu membuat TXMLDocument baru, maka Anda tidak harus membuat sebelumnya. Akan tetapi, pastikan untuk membersihkan dokumen dengan memanggil Free ketika Anda selesai.

Sebagai contoh, pertimbangkan XML berikut:

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

Contoh kode berikut menampilkan cara yang benar dan salah atas mendapatkan nilai node teks:

 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;

Menampilkan nama node

A quick note on navigating the DOM tree: When you need to access nodes in sequence, it is best to use FirstChild and NextSibling properties (to iterate forward), or LastChild and PreviousSibling (to iterate backward). For random access it is possible to use ChildNodes or GetElementsByTagName methods, but these will create a TDOMNodeList object which eventually must be freed. This differs from other DOM implementations like MSXML, because FCL implementation is object-based, not interface-based.

The following example shows how to print the names of nodes to a TMemo placed on a form.

Bellow is the XML file called 'C:\Programas\teste.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>

And here the Pascal code to execute the task:

 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;

This will print:

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

Menguraikan TreeView dengan XML

One common use of XML files is to parse them and show their contents in a tree like format. You can find the TTreeView component on the "Common Controls" tab on Lazarus.

The function below will take a XML document previously loaded from a file or generated on code, and will populate a TreeView with it´s contents. The caption of each node will be the content of the first attribute of each node.

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;

Memodifikasi dokumen 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:

   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;

And here an example method that will located 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.

procedure TForm1.actAddChildNode(Sender: TObject);
var
  Posicao: Integer;
  NovoNo: TDomNode;
begin
  {*******************************************************************
  *  Detects the selected element
  *******************************************************************}
  if TreeView1.Selected = nil then Exit;

  if TreeView1.Selected.Level = 0 then
  begin
    Posicao := TreeView1.Selected.Index;

    NovoNo := XMLDoc.CreateElement('item');
    TDOMElement(NovoNo).SetAttribute('nome', 'Item');
    TDOMElement(NovoNo).SetAttribute('arquivo', 'Arquivo');
    with XMLDoc.DocumentElement.ChildNodes do
    begin
      Item[Posicao].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;

Membuat TXMLDocument dari string

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

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;

Memvalidasi dokumen

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 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>

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:

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;

Link Eksternal