XML Tutorial/ko

From Free Pascal wiki
Jump to navigationJump to search

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>

XML 도큐먼트 수정 하기

먼저, 기억할 것은 TDOMDocument 는 DOM에 대한 핸들이라는 것이다. XML 도큐먼트를 로딩하거나 TDOMDocument 를 한개 생성하여 이 클래스의 인트턴스를 얻을 수 있다.

다른 한편으로 노드는 통상적인 객체처럼 생성될 수 없다. 생성하기 위해서는 *반드시* TDOMDocument에서 제공하는 메쏘드를 사용하여야 한다. 통상적인 객체는 트리상의 정확한 위치에 넣기 위해서 다른 메써드를 사용한다. 이는 노드는 DOM사의 특정한 도큐먼트에 의해 소유되어야하기 때문이다.

아래는 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>

다음은 선택된 아이템을 TTreeView상에 위치시키고 자식 노드를 그것이 표현하는 XML 도큐먼트에 삽입하는 예제 메쏘드를 보여 줄 것이다. TreeView는 XML2Tree 함수를 사용하여 XML 파일의 내용으로 먼져 채워져 있어야 한다.

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

 position: Integer;
 NovoNo: TDomNode;

begin

 {*******************************************************************
 *  선택된 원소를 찾고
 *******************************************************************}
 if TreeView1.Selected = nil then Exit;
 if TreeView1.Selected.Level = 0 then
 begin
   position := TreeView1.Selected.Index;
   NovoNo := XMLDoc.CreateElement('아이템');
   TDOMElement(NovoNo).SetAttribute('이름', '아이템');
   TDOMElement(NovoNo).SetAttribute('Heennavi', '흰나비');
   with XMLDoc.DocumentElement.ChildNodes do
   begin
     Item[position].AppendChild(NovoNo);
     Free;
   end;
   {*******************************************************************
   *  TreeView를 업데이트하고
   *******************************************************************}
   TreeView1.Items.Clear;
   XML2Tree(TreeView1, XMLDoc);
 end
 else if TreeView1.Selected.Level >= 1 then
 begin
   {*******************************************************************
   *  이 함수는 트리의 첫번째 수준에서만 동작하지만,
   *  어떤 수의 수준에서라도 동작할 수 있도록 쉽게 수정할 수 있다.
   *******************************************************************}
 end;

end; </delphi>

문자열로 부터 TXMLDocument 생성

MyXmlString에 있는 모든 XML 파일에서 다음 코드는 그것의 DOM을 생성할 것이다.

<delphi> Var

 S : TStringStream;
 XML : TXMLDocument;

begin

 S:= TStringStream.Create(MyXMLString);
 Try
   S.Position:=0;
   XML:=Nil;
   ReadXMLFile(XML,S); // 완전한 XML 도큐먼트
   //다른 방법으로는:
   ReadXMLFragment(AParentNode,S); // XML 조각들만 읽는다.
 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