Difference between revisions of "XML Tutorial"

From Lazarus wiki
Jump to navigationJump to search
(see also section)
(added try-finally sections as it is good practice)
Line 22: Line 22:
 
For instance, consider the following XML:
 
For instance, consider the following XML:
  
<xml>
+
<xml><?xml version="1.0"?>
<?xml version="1.0"?>
+
<request>
<request>
+
  <request_type>PUT_FILE</request_type>
  <request_type>PUT_FILE</request_type>
+
  <username>123</username>
  <username>123</username>
+
  <password>abc</password>
  <password>abc</password>
+
</request></xml>
</request>
 
</xml>
 
  
 
The following code example shows both the correct and the incorrect ways of getting the value of the text node (add the units '''XMLRead''' and '''DOM''' to the used units list):
 
The following code example shows both the correct and the incorrect ways of getting the value of the text node (add the units '''XMLRead''' and '''DOM''' to the used units list):
  
<delphi>
+
<delphi>var
var
 
 
   PassNode: TDOMNode;
 
   PassNode: TDOMNode;
   Doc:     TXMLDocument;
+
   Doc: TXMLDocument;
begin
+
begin
   // Read in xml file from disk
+
   try
  ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
+
    // Read in xml file from disk
  // Retrieve the "password" node
+
    ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
  PassNode := Doc.DocumentElement.FindNode('password');
+
    // Retrieve the "password" node
  // Write out value of the selected node
+
    PassNode := Doc.DocumentElement.FindNode('password');
  WriteLn(PassNode.NodeValue); // will be blank
+
    // Write out value of the selected node
  // The text of the node is actually a separate child node
+
    WriteLn(PassNode.NodeValue); // will be blank
  WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
+
    // The text of the node is actually a separate child node
  // alternatively
+
    WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
  WriteLn(PassNode.TextContent);
+
    // alternatively
   // finally, free the document
+
    WriteLn(PassNode.TextContent);
  Doc.Free;
+
   finally
end;
+
    // finally, free the document
</delphi>
+
    Doc.Free;
 +
  end;
 +
end;</delphi>
  
 
=== Printing the names of nodes ===
 
=== Printing the names of nodes ===
Line 61: Line 60:
 
Bellow is the XML file called 'C:\Programas\teste.xml':
 
Bellow is the XML file called 'C:\Programas\teste.xml':
  
<xml>
+
<xml><?xml version="1.0"?>
<?xml version="1.0"?>
+
<images directory="mydir">
<images directory="mydir">
 
 
   <imageNode URL="graphic.jpg" title="">
 
   <imageNode URL="graphic.jpg" title="">
 
     <Peca DestinoX="0" DestinoY="0">Pecacastelo.jpg1.swf</Peca>
 
     <Peca DestinoX="0" DestinoY="0">Pecacastelo.jpg1.swf</Peca>
 
     <Peca DestinoX="0" DestinoY="86">Pecacastelo.jpg2.swf</Peca>
 
     <Peca DestinoX="0" DestinoY="86">Pecacastelo.jpg2.swf</Peca>
 
   </imageNode>
 
   </imageNode>
</images>
+
</images></xml>
</xml>
 
  
 
And here the Pascal code to execute the task:
 
And here the Pascal code to execute the task:
  
<delphi>
+
<delphi>var
var
+
  Doc: TXMLDocument;
  Documento: TXMLDocument;
+
  Child: TDOMNode;
  Child: TDOMNode;
+
  j: Integer;
  j: Integer;
+
begin
begin
+
  try
  ReadXMLFile(Documento, 'C:\Programas\teste.xml');
+
    ReadXMLFile(Doc, 'C:\Documents\test.xml');
  Memo.Lines.Clear;
+
    Memo.Lines.Clear;
  // using FirstChild and NextSibling properties
+
    // using FirstChild and NextSibling properties
  Child := Documento.DocumentElement.FirstChild;
+
    Child := Doc.DocumentElement.FirstChild;
  while Assigned(Child) do
+
    while Assigned(Child) do
  begin
+
    begin
    Memo.Lines.Add(Child.NodeName + ' ' + Child.Attributes.Item[0].NodeValue);
+
      Memo.Lines.Add(Child.NodeName + ' ' + Child.Attributes.Item[0].NodeValue);
    // using ChildNodes method
+
      // using ChildNodes method
    with Child.ChildNodes do
+
      with Child.ChildNodes do
    try
+
      try
      for j := 0 to (Count - 1) do
+
        for j := 0 to (Count - 1) do
        Memo.Lines.Add(Item[j].NodeName + ' ' + Item[j].FirstChild.NodeValue);
+
          Memo.Lines.Add(Item[j].NodeName + ' ' + Item[j].FirstChild.NodeValue);
    finally
+
      finally
      Free;
+
        Free;
    end;
+
      end;
    Child := Child.NextSibling;
+
      Child := Child.NextSibling;
  end;
+
    end;
  Documento.Free;
+
  finally
end;
+
    Doc.Free;
</delphi>
+
  end;
 +
end;</delphi>
  
 
This will print:
 
This will print:
  
<pre>
+
<pre>imageNode graphic.jpg
imageNode graphic.jpg
 
Peca Pecacastelo.jpg1.swf
 
 
Peca Pecacastelo.jpg1.swf
 
Peca Pecacastelo.jpg1.swf
</pre>
+
Peca Pecacastelo.jpg1.swf</pre>
  
 
=== Populating a TreeView with XML ===
 
=== Populating a TreeView with XML ===
Line 114: Line 110:
 
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>
+
<delphi>procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
 
 
var
 
var
 
   iNode: TDOMNode;
 
   iNode: TDOMNode;
Line 128: Line 123:
 
     // Adds a node to the tree
 
     // Adds a node to the tree
 
     if Node.HasAttributes and (Node.Attributes.Length>0) then
 
     if Node.HasAttributes and (Node.Attributes.Length>0) then
       s:=Node.Attributes[0].NodeValue
+
       s := Node.Attributes[0].NodeValue
 
     else
 
     else
       s:='';  
+
       s := '';  
 
     TreeNode := tree.Items.AddChild(TreeNode, s);
 
     TreeNode := tree.Items.AddChild(TreeNode, s);
  
Line 151: Line 146:
 
     iNode := iNode.NextSibling;
 
     iNode := iNode.NextSibling;
 
   end;
 
   end;
end;
+
end;</delphi>
</delphi>
 
  
 
=== Modifying a XML document ===
 
=== Modifying a XML document ===
Line 162: Line 156:
 
Below are some common methods from TDOMDocument:
 
Below are some common methods from TDOMDocument:
  
<delphi>
+
<delphi>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;
+
function CreateCDATASection(const data: DOMString): TDOMCDATASection;
  function CreateCDATASection(const data: DOMString): TDOMCDATASection;
+
  virtual;
    virtual;
+
function CreateAttribute(const name: DOMString): TDOMAttr; virtual;</delphi>
  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 [[Networking#Populating a TreeView with XML|XML2Tree function]].
 
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 [[Networking#Populating a TreeView with XML|XML2Tree function]].
  
<delphi>
+
<delphi>procedure TForm1.actAddChildNode(Sender: TObject);
procedure TForm1.actAddChildNode(Sender: TObject);
 
 
var
 
var
 
   position: Integer;
 
   position: Integer;
Line 209: Line 200:
 
     *******************************************************************}
 
     *******************************************************************}
 
   end;
 
   end;
end;
+
end;</delphi>
</delphi>
 
  
 
=== Create a TXMLDocument from a string ===
 
=== Create a TXMLDocument from a string ===
Line 216: Line 206:
 
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>
+
<delphi>var
Var
+
   S: TStringStream;
   S : TStringStream;
+
   XML: TXMLDocument;
   XML : TXMLDocument;
 
 
 
 
begin
 
begin
   S:= TStringStream.Create(MyXMLString);
+
   S := TStringStream.Create(MyXMLString);
   Try
+
   try
     S.Position:=0;
+
     S.Position := 0;
     XML:=Nil;
+
     XML := nil;
     ReadXMLFile(XML,S); // Complete XML document
+
     ReadXMLFile(XML, S); // Complete XML document
 
     // Alternatively:
 
     // Alternatively:
     ReadXMLFragment(AParentNode,S); // Read only XML fragment.
+
     ReadXMLFragment(AParentNode, S); // Read only XML fragment.
   Finally
+
   finally
 
     S.Free;
 
     S.Free;
 
   end;
 
   end;
end;
+
end;</delphi>
</delphi>
 
  
 
=== Validating a document ===
 
=== Validating a document ===
Line 241: Line 228:
 
Here is an example of XML document with a DTD:
 
Here is an example of XML document with a DTD:
  
<xml>
+
<xml><?xml version='1.0'?>
  <?xml version='1.0'?>
+
<!DOCTYPE root [
  <!DOCTYPE root [
+
<!ELEMENT root (child)+ >
  <!ELEMENT root (child)+ >
+
<!ELEMENT child (#PCDATA)>
  <!ELEMENT child (#PCDATA)>
+
]>
  ]>
+
<root>
  <root>
+
  <child>This is a first child.</child>
    <child>This is a first child.</child>
+
  <child>And this is the second one.</child>
    <child>And this is the second one.</child>
+
</root></xml>
  </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.
 
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 257: Line 242:
 
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>
+
<delphi>procedure TMyObject.DOMFromStream(AStream: TStream);
procedure TMyObject.DOMFromStream(AStream: TStream);
 
 
var
 
var
 
   Parser: TDOMParser;
 
   Parser: TDOMParser;
Line 264: Line 248:
 
   TheDoc: TXMLDocument;
 
   TheDoc: TXMLDocument;
 
begin
 
begin
   // create a parser object
+
   try
  Parser := TDOMParser.Create;
+
    // create a parser object
  // and the input source
+
    Parser := TDOMParser.Create;
  Src := TXMLInputSource.Create(AStream);
+
    // and the input source
  // we want validation
+
    Src := TXMLInputSource.Create(AStream);
  Parser.Options.Validate := True;
+
    // we want validation
  // assign a error handler which will receive notifications
+
    Parser.Options.Validate := True;
  Parser.OnError := @ErrorHandler;
+
    // assign a error handler which will receive notifications
  // now do the job
+
    Parser.OnError := @ErrorHandler;
  Parser.Parse(Src, TheDoc);
+
    // now do the job
  // ...and cleanup
+
    Parser.Parse(Src, TheDoc);
   Src.Free;
+
    // ...and cleanup
  Parser.Free;
+
   finally
 +
    Src.Free;
 +
    Parser.Free;
 +
  end;
 
end;
 
end;
  
Line 283: Line 270:
 
   if E.Severity = esError then  // we are interested in validation errors only
 
   if E.Severity = esError then  // we are interested in validation errors only
 
     writeln(E.Message);
 
     writeln(E.Message);
end;
+
end;</delphi>
</delphi>
 
  
 
=== Generating a XML file ===
 
=== Generating a XML file ===
Line 292: Line 278:
 
Please, remember DOM and XMLWrite libs in uses clause
 
Please, remember DOM and XMLWrite libs in uses clause
  
<delphi>
+
<delphi>unit Unit1;
unit Unit1;
 
  
 
{$mode objfpc}{$H+}
 
{$mode objfpc}{$H+}
Line 325: Line 310:
 
procedure TForm1.Button1Click(Sender: TObject);
 
procedure TForm1.Button1Click(Sender: TObject);
 
var
 
var
   xdoc: TXMLDocument;                                  // variable to document
+
   Doc: TXMLDocument;                                  // variable to document
 
   RootNode, parentNode, nofilho: TDOMNode;                    // variable to nodes
 
   RootNode, parentNode, nofilho: TDOMNode;                    // variable to nodes
 
begin
 
begin
   //create a document
+
   try
  xdoc := TXMLDocument.create;
+
    // Create a document
 +
    Doc := TXMLDocument.Create;
  
  //create a root node
+
    // Create a root node
  RootNode := xdoc.CreateElement('register');
+
    RootNode := Doc.CreateElement('register');
  Xdoc.Appendchild(RootNode);                          // save root node
+
    Doc.Appendchild(RootNode);                          // save root node
 +
 
 +
    // Create a parent node
 +
    RootNode:= Doc.DocumentElement;
 +
    parentNode := Doc.CreateElement('usuario');
 +
    TDOMElement(parentNode).SetAttribute('id', '001');      // create atributes to parent node
 +
    RootNode.Appendchild(parentNode);                          // save parent node
  
  //create a parent node
+
    // Create a child node
  RootNode:= xdoc.DocumentElement;
+
    parentNode := Doc.CreateElement('nome');                // create a child node
  parentNode := xdoc.CreateElement('usuario');
+
    // TDOMElement(parentNode).SetAttribute('sexo', 'M');    // create atributes
  TDOMElement(parentNode).SetAttribute('id', '001');       // create atributes to parent node
+
    nofilho := Doc.CreateTextNode('Fernando');         // insert a value to node
  RootNode.Appendchild(parentNode);                         // save parent node
+
    parentNode.Appendchild(nofilho);                        // save node
 +
    RootNode.ChildNodes.Item[0].AppendChild(parentNode);      // insert child node in respective parent node
 +
 +
    // Create a child node
 +
    parentNode := Doc.CreateElement('idade');               // create a child node
 +
    // TDOMElement(parentNode).SetAttribute('ano', '1976');   // create atributes
 +
    nofilho := Doc.CreateTextNode('32');              // insert a value to node
 +
    parentNode.Appendchild(nofilho);                        // save node
 +
    RootNode.ChildNodes.Item[0].AppendChild(parentNode);       // insert a childnode in respective parent node
  
  //create a child node
+
     writeXMLFile(Doc, 'test.xml');                    // write to XML
  parentNode := xdoc.CreateElement('nome');                // create a child node
+
   finally
  //TDOMElement(parentNode).SetAttribute('sexo', 'M');     // create atributes
+
    Doc.Free;                                          // free memory
  nofilho := xdoc.CreateTextNode('Fernando');        // insert a value to node
+
  end;
  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
 
  RootNode.ChildNodes.Item[0].AppendChild(parentNode);      // insert a childnode in respective parent node
 
 
 
  writeXMLFile(xDoc,'teste.xml');                    // write to XML
 
   Xdoc.free;                                          // free memory
 
 
end;
 
end;
  
Line 362: Line 350:
 
   {$I unit1.lrs}
 
   {$I unit1.lrs}
  
end.
+
end.</delphi>
</delphi>
 
  
 
The  result will be the XML file below:
 
The  result will be the XML file below:
<xml>
+
<xml><?xml version="1.0"?>
<?xml version="1.0"?>
 
 
<register>
 
<register>
 
   <usuario id="001">
 
   <usuario id="001">
Line 373: Line 359:
 
     <idade>32</idade>
 
     <idade>32</idade>
 
   </usuario>
 
   </usuario>
</register>
+
</register></xml>
</xml>
 
  
 
--[[User:Fernandosinesio|Fernandosinesio]] 22:28, 24 April 2008 (CEST)fernandosinesio@gmail.com
 
--[[User:Fernandosinesio|Fernandosinesio]] 22:28, 24 April 2008 (CEST)fernandosinesio@gmail.com

Revision as of 13:10, 23 December 2010

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)

Introduction

The Extensible Markup Language is a 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.

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.

The XML DOM (Document Object Model) is a set of standarized objects that provide a similar interface for using 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 XML DOM 1.0.

Examples

Bellow there is a list of XML data manipulation examples with growing complexity.

Reading a text node

For Delphi Programmers: Note that when working with TXMLDocument, the text within a Node is considered a separate TEXT Node. As 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.

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.

For instance, consider the following XML:

<xml><?xml version="1.0"?> <request>

 <request_type>PUT_FILE</request_type>
 <username>123</username>
 <password>abc</password>

</request></xml>

The following code example shows both the correct and the incorrect ways of getting the value of the text node (add the units XMLRead and DOM to the used units list):

<delphi>var

 PassNode: TDOMNode;
 Doc: TXMLDocument;

begin

 try
   // 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
   // finally, free the document
   Doc.Free;
 end;

end;</delphi>

Printing the names of nodes

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

And here the Pascal code to execute the task:

<delphi>var

 Doc: TXMLDocument;
 Child: TDOMNode;
 j: Integer;

begin

 try
   ReadXMLFile(Doc, 'C:\Documents\test.xml');
   Memo.Lines.Clear;
   // using FirstChild and NextSibling properties
   Child := Doc.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;
 finally
   Doc.Free;
 end;

end;</delphi>

This will print:

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

Populating a TreeView with 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.

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

 iNode: TDOMNode;
 procedure ProcessNode(Node: TDOMNode; TreeNode: TTreeNode);
 var
   cNode: TDOMNode;
   s: string;
 begin
   if Node = nil then Exit; // Stops if reached a leaf
   
   // Adds a node to the tree
   if Node.HasAttributes and (Node.Attributes.Length>0) then
     s := Node.Attributes[0].NodeValue
   else
     s := ; 
   TreeNode := tree.Items.AddChild(TreeNode, s);
   // 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>

Modifying a XML document

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>

Create a TXMLDocument from a string

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>

Validating a document

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

 try
   // 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
 finally
   Src.Free;
   Parser.Free;
 end;

end;

procedure TMyObject.ErrorHandler(E: EXMLReadError); begin

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

end;</delphi>

Generating a XML file

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

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

begin

 try
   // Create a document
   Doc := TXMLDocument.Create;
   // Create a root node
   RootNode := Doc.CreateElement('register');
   Doc.Appendchild(RootNode);                           // save root node
 
   // Create a parent node
   RootNode:= Doc.DocumentElement;
   parentNode := Doc.CreateElement('usuario');
   TDOMElement(parentNode).SetAttribute('id', '001');       // create atributes to parent node
   RootNode.Appendchild(parentNode);                          // save parent node
   // Create a child node
   parentNode := Doc.CreateElement('nome');                // create a child node
   // TDOMElement(parentNode).SetAttribute('sexo', 'M');     // create atributes
   nofilho := Doc.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 := Doc.CreateElement('idade');               // create a child node
   // TDOMElement(parentNode).SetAttribute('ano', '1976');   // create atributes
   nofilho := Doc.CreateTextNode('32');               // insert a value to node
   parentNode.Appendchild(nofilho);                         // save node
   RootNode.ChildNodes.Item[0].AppendChild(parentNode);       // insert a childnode in respective parent node
   writeXMLFile(Doc, 'test.xml');                     // write to XML
 finally
   Doc.Free;                                          // free memory
 end;

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

Encoding

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.

See also

External Links