Difference between revisions of "XML Tutorial/ko"

From Free Pascal wiki
Jump to navigationJump to search
Line 113: Line 113:
 
XML 파일을 사용하는 일반적인 것은 파싱하고트리와 같은 형식으로 내용을 보여주고자 함일 것이다. 라자루스의 "Common Controls" 탭에서 TTreeView 컴포넌트를 찾을 수 있을 것이다.
 
XML 파일을 사용하는 일반적인 것은 파싱하고트리와 같은 형식으로 내용을 보여주고자 함일 것이다. 라자루스의 "Common Controls" 탭에서 TTreeView 컴포넌트를 찾을 수 있을 것이다.
  
아래의 함수는 파일로 부터
+
아래에 있는 이 함수는 이미 파일에서 로드되거나 코드에서 생성된 XML 도큐먼드를 가져 올 것이며, 그 내용을 TreeView에 넣어 줄 것이다. 각 노드의 캡션은 각 노드의 첫번째 속성 값이 될 것이다.
 
 
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>
Line 126: Line 124:
 
     cNode: TDOMNode;
 
     cNode: TDOMNode;
 
   begin
 
   begin
     if Node = nil then Exit; // Stops if reached a leaf
+
     if Node = nil then Exit; // leaf에 도달하면 정지
 
      
 
      
     // Adds a node to the tree
+
     // 노드를 트리에 추가
 
     TreeNode := tree.Items.AddChild(TreeNode, Node.Attributes[0].NodeValue);
 
     TreeNode := tree.Items.AddChild(TreeNode, Node.Attributes[0].NodeValue);
  
     // Goes to the child node
+
     // 차일드 노드로 감
 
     cNode := Node.FirstChild;
 
     cNode := Node.FirstChild;
  
     // Processes all child nodes
+
     // 모든 차일드 노드를 처리
 
     while cNode <> nil do
 
     while cNode <> nil do
 
     begin
 
     begin
Line 146: Line 144:
 
   while iNode <> nil do
 
   while iNode <> nil do
 
   begin
 
   begin
     ProcessNode(iNode, nil); // Recursive
+
     ProcessNode(iNode, nil); // 회귀
 
     iNode := iNode.NextSibling;
 
     iNode := iNode.NextSibling;
 
   end;
 
   end;

Revision as of 13:17, 11 June 2009

Template:XML 튜토리얼

소개

확장 가능한 마크업 언어는 W3C가 추천하는 언어로서 다른 시스템간에 정보를 교환하기 위해 만들어 졌다. 텍스트 기반으로 정보를 저장한다. 현대의 XHTML 같은 데이터 교환 언어와 대부분의 웹서비스 기술은 XML에 기초를 두고 있다.

현대 프리 파스칼에서 XML을 위해 지원하는 유닛의 셑이 있다. 이러한 유닛은 "XMLRead", "XMLWrite" 및 "DOM" 이라고 불리며 이들은 프리파스칼 컴파일러상의 프리컴포넌트 라이브러리(FCL)의 일부이다. FCL은 현재(2005년 10월) 문서화 되어있지 않으므로 이 간단한 튜토리얼은 이와같은 유닛을 통해 XML에 접근한다는 것을 소개하고자 함이다.

XML DOM(Document Object Model) 은 표준화된 객체의 집합으로다른 언어와 기종을 사용해서 유사한 인터페이스를 제공해 준다. 표준은 객체의 메써드, 프로퍼티 및 다른 인터페이스 부분만을 명기할 뿐이며, 다른 언어에서 구현하는 것은 자유스럽게 놔둔다. FCL은 현재 XML DOM 1.0 을 모두 지원한다.

예제

아래에 점점 복잡해지는 XML 데이터 조작에 관한 리스트가 있다.

텍스트 노드 읽기

델파이 프로그래머를 위해: TXMLDocument로 작업한다면 Node사이에 있는 텍스트는 분리된 TEXT Node로 고려해야한다는 것을 명심해야 한다. 그 결과 노드의 텍스트 값은 분리된 노으로서 접금해야 한다. 또한, TextContent 프로퍼티는 주어진 한개( 같이 연결된)의 하부에 있는 모든 텍스트 노드의 내용을 받을 수 있다.

ReadXMLFile 프로시져는 항상 새로운 TXMLDocument 를 생성하므로 직접 생성할 필요가 없다. 그러나 이럴 경우 반드시 Free 를 콜하여 도큐먼트를 해제하여야 한다는 것을 명심하라.

예를 들어, 다음 XML을 생각해보자:

<xml>

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

</xml>

다음 코드는 텍스트 노드의 값을 정확하게, 부정확하게 가져오는 예를 보여준다:

<delphi>

var
 PassNode: TDOMNode;
 Doc:      TXMLDocument;
begin
 // 디스크에서 xml 파일을 읽는다
 ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
 // "password"를 가져온다
 PassNode := Doc.DocumentElement.FindNode('password');
 // 선택된 노드의 값을 쓴다
 WriteLn(PassNode.NodeValue); // will be blank
 // 노드의 텍스트는 실제는 분리왼 자식 노드이다
 WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
 // 다른 방법으로
 WriteLn(PassNode.TextContent);
 // 마지막으로 도큐먼트를 해제한다.
 Doc.Free;

end; </delphi>

노드의 이름을 프린드 하기

DOM 트리를 살펴보는 간단한 노트: 노드를 순차적으로 접근하려고 한다면, FirstChildNextSibling 프로퍼티( 전방으로 재귀호출 하기 위해)를 사용하거나 LastChildPreviousSibling (후방으로 재귀호출) 것이 최상의 방법이다. 랜덤 접근을 위해서는 ChildNodes 또는 GetElementsByTagName 메쏘드를 사용할 수 있으나, 이것들은 TDOMNodeList 객체를 생상하므로 반드시 해제 해 주어야 한다. 이것은 MSXML 같은 다른 DOM 구현과는 다르다. 이는 FCL 구현이 객체를 기반으로 한 것이지 인터페이스를 기반으로 한것이 안기 때문이다.

다음 예제는 폼에 잇는 TMemo에 노드의 이름을 프린트 하는 방법을 보여준다.

아래는 'C:\Programas\teste.xml'로 불리는 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>

다음은 태스크를 실행하기 위한 파스칼 코드이다:

<delphi>

var
  Documento: TXMLDocument;
  Child: TDOMNode;
  j: Integer;
begin
  ReadXMLFile(Documento, 'C:\Programas\teste.xml');
  Memo.Lines.Clear;
  // FirstChild 와 NextSibling 프로퍼티를 사용하여
  Child := Documento.DocumentElement.FirstChild;
  while Assigned(Child) do
  begin
    Memo.Lines.Add(Child.NodeName + ' ' + Child.Attributes.Item[0].NodeValue);
    // ChildNodes 메쏘드 사용
    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>

이것은 다음과같이 프린트할 것이다:

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

TreeView 를 XML과 함께 넣기

XML 파일을 사용하는 일반적인 것은 파싱하고트리와 같은 형식으로 내용을 보여주고자 함일 것이다. 라자루스의 "Common Controls" 탭에서 TTreeView 컴포넌트를 찾을 수 있을 것이다.

아래에 있는 이 함수는 이미 파일에서 로드되거나 코드에서 생성된 XML 도큐먼드를 가져 올 것이며, 그 내용을 TreeView에 넣어 줄 것이다. 각 노드의 캡션은 각 노드의 첫번째 속성 값이 될 것이다.

<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; // leaf에 도달하면 정지
   
   // 노드를 트리에 추가
   TreeNode := tree.Items.AddChild(TreeNode, Node.Attributes[0].NodeValue);
   // 차일드 노드로 감
   cNode := Node.FirstChild;
   // 모든 차일드 노드를 처리
   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); // 회귀
   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

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

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

 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

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.

External Links


Multithreaded Application Tutorial