Sign in Join
Wiki copytemporary

XML Tutorial/id: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: XML Tutorial/id

OldNewLine
1+## Pengenalan
2+
3+Extensible Markup Language adalah bahasa yang direkomendasikan oleh [W3C](http://www.w3.org/) 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.
4+
5+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.
6+
7+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](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/).
8+
9+## Contoh
10+
11+Di bawah ada daftar contoh manipulasi data XML dengan perkembangan yang kompleks.
12+
13+### Membaca node teks
14+
15+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.
16+
17+Prosedur **ReadXMLFile** selalu membuat **TXMLDocument** baru, maka Anda tidak harus membuat sebelumnya. Akan tetapi, pastikan untuk membersihkan dokumen dengan memanggil **Free** ketika Anda selesai.
18+
19+Sebagai contoh, pertimbangkan XML berikut:
20+
21+``` xml
22+ <?xml version="1.0"?>
23+ <request>
24+ <request_type>PUT_FILE</request_type>
25+ <username>123</username>
26+ <password>abc</password>
27+ </request>
28+```
29+
30+Contoh kode berikut menampilkan cara yang benar dan salah atas mendapatkan nilai node teks:
31+
32+``` pascal
33+ var
34+ PassNode: TDOMNode;
35+ Doc: TXMLDocument;
36+ begin
37+ // Read in xml file from disk
38+ ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
39+ // Retrieve the "password" node
40+ PassNode := Doc.DocumentElement.FindNode('password');
41+ // Write out value of the selected node
42+ WriteLn(PassNode.NodeValue); // will be blank
43+ // The text of the node is actually a separate child node
44+ WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
45+ // alternatively
46+ WriteLn(PassNode.TextContent);
47+ // finally, free the document
48+ Doc.Free;
49+end;
50+```
51+
52+### Menampilkan nama node
53+
54+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.
55+
56+The following example shows how to print the names of nodes to a TMemo placed on a form.
57+
58+Bellow is the XML file called 'C:\Programas\teste.xml':
59+
60+``` xml
61+ <?xml version="1.0"?>
62+ <images directory="mydir">
63+ <imageNode URL="graphic.jpg" title="">
64+ <Peca DestinoX="0" DestinoY="0">Pecacastelo.jpg1.swf</Peca>
65+ <Peca DestinoX="0" DestinoY="86">Pecacastelo.jpg2.swf</Peca>
66+ </imageNode>
67+ </images>
68+```
69+
70+And here the Pascal code to execute the task:
71+
72+``` pascal
73+ var
74+ Documento: TXMLDocument;
75+ Child: TDOMNode;
76+ j: Integer;
77+ begin
78+ ReadXMLFile(Documento, 'C:\Programas\teste.xml');
79+ Memo.Lines.Clear;
80+ // using FirstChild and NextSibling properties
81+ Child := Documento.DocumentElement.FirstChild;
82+ while Assigned(Child) do
83+ begin
84+ Memo.Lines.Add(Child.NodeName + ' ' + Child.Attributes.Item[0].NodeValue);
85+ // using ChildNodes method
86+ with Child.ChildNodes do
87+ try
88+ for j := 0 to (Count - 1) do
89+ Memo.Lines.Add(Item[j].NodeName + ' ' + Item[j].FirstChild.NodeValue);
90+ finally
91+ Free;
92+ end;
93+ Child := Child.NextSibling;
94+ end;
95+ Documento.Free;
96+ end;
97+```
98+
99+This will print:
100+
101+ imageNode graphic.jpg
102+ Peca Pecacastelo.jpg1.swf
103+ Peca Pecacastelo.jpg1.swf
104+
105+### Menguraikan TreeView dengan XML
106+
107+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.
108+
109+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.
110+
111+``` pascal
112+procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
113+var
114+ iNode: TDOMNode;
115+
116+ procedure ProcessNode(Node: TDOMNode; TreeNode: TTreeNode);
117+ var
118+ cNode: TDOMNode;
119+ begin
120+ if Node = nil then Exit; // Stops if reached a leaf
121+
122+ // Adds a node to the tree
123+ TreeNode := tree.Items.AddChild(TreeNode, Node.Attributes[0].NodeValue);
124+
125+ // Goes to the child node
126+ cNode := Node.FirstChild;
127+
128+ // Processes all child nodes
129+ while cNode <> nil do
130+ begin
131+ ProcessNode(cNode, TreeNode);
132+ cNode := cNode.NextSibling;
133+ end;
134+ end;
135+
136+begin
137+ iNode := XMLDoc.DocumentElement.FirstChild;
138+ while iNode <> nil do
139+ begin
140+ ProcessNode(iNode, nil); // Recursive
141+ iNode := iNode.NextSibling;
142+ end;
143+end;
144+```
145+
146+### Memodifikasi dokumen XML
147+
148+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.
149+
150+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.
151+
152+Below are some common methods from TDOMDocument:
153+
154+``` pascal
155+ function CreateElement(const tagName: DOMString): TDOMElement; virtual;
156+ function CreateTextNode(const data: DOMString): TDOMText;
157+ function CreateCDATASection(const data: DOMString): TDOMCDATASection;
158+ virtual;
159+ function CreateAttribute(const name: DOMString): TDOMAttr; virtual;
160+```
161+
162+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|XML2Tree function]].
163+
164+``` pascal
165+procedure TForm1.actAddChildNode(Sender: TObject);
166+var
167+ Posicao: Integer;
168+ NovoNo: TDomNode;
169+begin
170+ {*******************************************************************
171+ * Detects the selected element
172+ *******************************************************************}
173+ if TreeView1.Selected = nil then Exit;
174+
175+ if TreeView1.Selected.Level = 0 then
176+ begin
177+ Posicao := TreeView1.Selected.Index;
178+
179+ NovoNo := XMLDoc.CreateElement('item');
180+ TDOMElement(NovoNo).SetAttribute('nome', 'Item');
181+ TDOMElement(NovoNo).SetAttribute('arquivo', 'Arquivo');
182+ with XMLDoc.DocumentElement.ChildNodes do
183+ begin
184+ Item[Posicao].AppendChild(NovoNo);
185+ Free;
186+ end;
187+
188+ {*******************************************************************
189+ * Updates the TreeView
190+ *******************************************************************}
191+ TreeView1.Items.Clear;
192+ XML2Tree(TreeView1, XMLDoc);
193+ end
194+ else if TreeView1.Selected.Level >= 1 then
195+ begin
196+ {*******************************************************************
197+ * This function only works on the first level of the tree,
198+ * but can easely modifyed to work for any number of levels
199+ *******************************************************************}
200+ end;
201+end;
202+```
203+
204+### Membuat TXMLDocument dari string
205+
206+Given al XML file in MyXmlString, the following code will create it's DOM:
207+
208+``` pascal
209+Var
210+ S : TStringStream;
211+ XML : TXMLDocument;
212+
213+begin
214+ S:= TStringStream.Create(MyXMLString);
215+ Try
216+ S.Position:=0;
217+ XML:=Nil;
218+ ReadXMLFile(XML,S); // Complete XML document
219+ // Alternatively:
220+ ReadXMLFragment(AParentNode,S); // Read only XML fragment.
221+ Finally
222+ S.Free;
223+ end;
224+end;
225+```
226+
227+### Memvalidasi dokumen
228+
229+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).
230+
231+Here is an example of XML document with a DTD:
232+
233+``` xml
234+ <?xml version='1.0'?>
235+ <!DOCTYPE root [
236+ <!ELEMENT root (child)+ >
237+ <!ELEMENT child (#PCDATA)>
238+ ]>
239+ <root>
240+ <child>This is a first child.</child>
241+ <child>And this is the second one.</child>
242+ </root>
243+```
244+
245+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.
246+
247+Loading such document is slightly more complicated. Let's assume we have XML data in a TStream object:
248+
249+``` pascal
250+procedure TMyObject.DOMFromStream(AStream: TStream);
251+var
252+ Parser: TDOMParser;
253+ Src: TXMLInputSource;
254+ TheDoc: TXMLDocument;
255+begin
256+ // create a parser object
257+ Parser := TDOMParser.Create;
258+ // and the input source
259+ Src := TXMLInputSource.Create(AStream);
260+ // we want validation
261+ Parser.Options.Validate := True;
262+ // assign a error handler which will receive notifications
263+ Parser.OnError := @ErrorHandler;
264+ // now do the job
265+ Parser.Parse(Src, TheDoc);
266+ // ...and cleanup
267+ Src.Free;
268+ Parser.Free;
269+end;
270+
271+procedure TMyObject.ErrorHandler(E: EXMLReadError);
272+begin
273+ if E.Severity = esError then // we are interested in validation errors only
274+ writeln(E.Message);
275+end;
276+```
277+
278+## Link Eksternal
279+
280+- [W3Schools](http://www.w3schools.com/xml/default.asp) Xml Tutorial
281+
282+- [Thomas Zastrow article](http://www.thomas-zastrow.de/texte/fpcxml/index.php) FPC and XML
283+
284+---
285+*From the Free Pascal wiki, page "XML Tutorial/id", as it stood on 2020-03-02 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history