Difference between revisions of "XML Tutorial/ko"

From Lazarus wiki
Jump to navigationJump to search
(New page: {{XML 튜토리얼}} == 소개== 확장 가능한 마크업 언어는 [http://www.w3.org/ W3C]가 추천하는 언어로서 다른 시스템간에 정보를 교환하기 위해 만들어...)
 
m (Fixed syntax highlighting)
 
(24 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{XML 튜토리얼}}
+
{{XML Tutorial}}
  
 
== 소개==
 
== 소개==
Line 5: Line 5:
 
확장 가능한 마크업 언어는 [http://www.w3.org/ W3C]가 추천하는 언어로서 다른 시스템간에 정보를 교환하기 위해 만들어 졌다. 텍스트 기반으로 정보를 저장한다. 현대의 XHTML 같은 데이터 교환 언어와 대부분의 웹서비스 기술은 XML에 기초를 두고 있다.  
 
확장 가능한 마크업 언어는 [http://www.w3.org/ W3C]가 추천하는 언어로서 다른 시스템간에 정보를 교환하기 위해 만들어 졌다. 텍스트 기반으로 정보를 저장한다. 현대의 XHTML 같은 데이터 교환 언어와 대부분의 웹서비스 기술은 XML에 기초를 두고 있다.  
  
현대 프리 파스칼에서 XML을 위해 지원하는 유닛의 셑이 있다. 이러한 유닛은  "XMLRead", "XMLWrite" 및 "DOM" 이라고 불리며 이들은 프리파스칼 컴파일러상의 프리컴포넌트 라이브러리(FCL)의 일부이다. FCL은 현재(2005년 10월) 문서화 되어있지 않으므로 이 간단한 튜토리얼은 이와같은 유닛을 통해 XML에 접근한다는 것을 소개하고자 함이다.
+
현대 프리 파스칼에서 XML을 위해 지원하는 유닛의 셋이 있다. 이러한 유닛은  "XMLRead", "XMLWrite" 및 "DOM" 이라고 불리며 이들은 프리파스칼 컴파일러상의 프리컴포넌트 라이브러리(FCL)의 일부이다. FCL은 현재(2005년 10월) 문서화 되어있지 않으므로 이 간단한 튜토리얼은 이와같은 유닛을 통해 XML에 접근한다는 것을 소개하고자 함이다.
  
XML DOM(Document Object Model) 은 표준화된 객체의 집합으로다른 언어와 기종을 사용해서 유사한 인터페이스를 제공해 준다. 표준은 객체의 메써드, 프로퍼티 및 다른 인터페이스 부분만을 명기할 뿐이며,  다른 언어에서 구현하는 것은 자유스럽게 놔둔다. FCL은 현재 [http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ XML DOM 1.0] 을 모두 지원한다.
+
XML DOM(Document Object Model) 은 표준화된 객체의 집합으로다른 언어와 기종을 사용해서 유사한 인터페이스를 제공해 준다. 표준은 객체의 메써드, 프로퍼티 및 다른 인터페이스 부분만을 명기할 뿐이며,  다른 언어에서 구현하는 것은 자유스럽게 놔둔다. FCL은 현재 [http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ XML DOM 2.0] 을 모두 지원하고 [http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/ XML DOM 3.0] 중 [[dom|이곳]]에 리스트한 서브셋을 지원한다.
  
== 예제 ==
+
== 유용한 예제 ==
  
Bellow there is a list of XML data manipulation examples with growing complexity.
+
아래에 점점 복잡해지는 XML 데이터 조작에 관한 리스트가 있다.
  
=== Reading a text node ===
+
===uses 절에 있는 유닛: Unicode 또는 Ansi===
  
For Delphi Programmers:
+
FPC는 ansi로 인코딩 된 루틴을 이용할 수 있는 XML 유닛을 포함하므로 각 플랫폼에의 인코딩은 달라질 수 있으며 Unicode가 아닐 수 있다. 라자루스는 LaxUtils 패키지에 모든 플랫폼에서 UTF-8 유니코드를 완전히 지원하는 각기 다른 XML 유닛의 서브셋을 가진다. 이 유닛은 상호 호환성이 있어 uses 절만 바꿈으로써 다른 것으로 바꿀 수 있다.
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.
+
시스템 인코딩에서 인코딩 된 문자열을 사용하는 FPC XML 유닛은 다음과 같다: DOM, XMLRead, XMLWrite, XMLCfg, XMLUtils, XMLStreaming.  
  
For instance, consider the following XML:
+
완전히 UTF-8 유니코드를 지원하는 라지루스 XML을 지원하는 유닛은 다음과 같다: laz2_DOM, laz2_XMLRead, laz2_XMLWrite, laz2_XMLCfg, laz2_XMLUtils, laz_XMLStreaming.
  
<xml>
+
모든 예제에서 위의 모든 유닛을 포함하는 것은 아니다.
 +
 
 +
=== 텍스트 노드 읽기 ===
 +
 
 +
델파이 프로그래머를 위해:
 +
TXMLDocument로 작업한다면 Node사이에 있는 텍스트는 분리된 TEXT Node로 고려해야한다는 것을 명심해야 한다. 그 결과 노드의 텍스트 값은 분리된 노으로서 접근해야 한다.
 +
또한, '''TextContent''' 프로퍼티는 주어진 한개( 같이 연결된)의 하부에 있는  모든 텍스트 노드의 내용을 받을 수 있다.
 +
 
 +
'''ReadXMLFile''' 프로시져는 항상 새로운 '''TXMLDocument''' 를 생성하므로 직접 생성할 필요가 없다. 그러나 이럴 경우 반드시 '''Free''' 를 콜하여 도큐먼트를 해제하여야 한다는 것을 명심하라.
 +
 
 +
예를 들어, 다음 XML을 생각해보자:
 +
 
 +
<syntaxhighlight lang="xml">
 
  <?xml version="1.0"?>
 
  <?xml version="1.0"?>
 
  <request>
 
  <request>
Line 29: Line 40:
 
   <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:
+
다음 코드는 텍스트 노드에서 값을 검색하는 경우의 올바른 방법과 틀린 방법을 보여 준다:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
  var
 
  var
 
   PassNode: TDOMNode;
 
   PassNode: TDOMNode;
 
   Doc:      TXMLDocument;
 
   Doc:      TXMLDocument;
 
  begin
 
  begin
   // Read in xml file from disk
+
   // 디스크에서 xml 파일을 읽는다
 
   ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
 
   ReadXMLFile(Doc, 'c:\xmlfiles\test.xml');
   // Retrieve the "password" node
+
   // "password"를 가져온다
 
   PassNode := Doc.DocumentElement.FindNode('password');
 
   PassNode := Doc.DocumentElement.FindNode('password');
   // Write out value of the selected node
+
   // 선택된 노드의 값을 쓴다
 
   WriteLn(PassNode.NodeValue); // will be blank
 
   WriteLn(PassNode.NodeValue); // will be blank
   // The text of the node is actually a separate child node
+
   // 노드의 텍스트는 실제는 분리왼 자식 노드이다
 
   WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
 
   WriteLn(PassNode.FirstChild.NodeValue); // correctly prints "abc"
   // alternatively
+
   // 다른 방법으로
 
   WriteLn(PassNode.TextContent);
 
   WriteLn(PassNode.TextContent);
   // finally, free the document
+
   // 마지막으로 도큐먼트를 해제한다.
 
   Doc.Free;
 
   Doc.Free;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
=== 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.
+
DOM 트리를 살펴보는 간단한 노트: 노드를 순차적으로 접근하려고 한다면, '''FirstChild''' '''NextSibling''' 프로퍼티( 전방으로 재귀호출 하기 위해)를 사용하거나 '''LastChild''' '''PreviousSibling''' (후방으로 재귀호출) 것이 최상의 방법이다. 랜덤 접근을 위해서는 '''ChildNodes''' 또는 '''GetElementsByTagName''' 메쏘드를 사용할 수 있으나, 이것들은 TDOMNodeList 객체를 생상하므로 반드시 해제 해 주어야 한다. 이것은 MSXML 같은 다른 DOM 구현과는 다르다. 이는 FCL 구현이 객체를 기반으로 한 것이지 인터페이스를 기반으로 한 것이 아니기 때문이다.
  
The following example shows how to print the names of nodes to a TMemo placed on a form.
+
다음 예제는 폼에 잇는 TMemo에 노드의 이름을 프린트 하는 방법을 보여준다.
  
Bellow is the XML file called 'C:\Programas\teste.xml':
+
아래는 'C:\Programas\teste.xml'로 불리는 XML 파일이다:
  
<xml>
+
<syntaxhighlight lang="xml">
 
  <?xml version="1.0"?>
 
  <?xml version="1.0"?>
 
  <images directory="mydir">
 
  <images directory="mydir">
Line 69: Line 80:
 
   </imageNode>
 
   </imageNode>
 
  </images>
 
  </images>
</xml>
+
</syntaxhighlight>
  
And here the Pascal code to execute the task:
+
다음은 태스크를 실행하기 위한 파스칼 코드이다:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
  var
 
  var
 
   Documento: TXMLDocument;
 
   Documento: TXMLDocument;
Line 81: Line 92:
 
   ReadXMLFile(Documento, 'C:\Programas\teste.xml');
 
   ReadXMLFile(Documento, 'C:\Programas\teste.xml');
 
   Memo.Lines.Clear;
 
   Memo.Lines.Clear;
   // using FirstChild and NextSibling properties
+
   // FirstChild NextSibling 프로퍼티를 사용하여
 
   Child := Documento.DocumentElement.FirstChild;
 
   Child := Documento.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
+
     // ChildNodes 메쏘드 사용
 
     with Child.ChildNodes do
 
     with Child.ChildNodes do
 
     try
 
     try
Line 98: Line 109:
 
   Documento.Free;
 
   Documento.Free;
 
  end;
 
  end;
</delphi>
+
</syntaxhighlight>
  
This will print:
+
이것은 다음과같이 프린트할 것이다:
  
 
<pre>
 
<pre>
Line 108: Line 119:
 
</pre>
 
</pre>
  
=== Populating a TreeView with XML ===
+
=== TreeView 를 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.
+
XML 파일을 사용하는 일반적인 것은 파싱하고트리와 같은 형식으로 내용을 보여주고자 함일 것이다. 라자루스의 "Common Controls" 탭에서 TTreeView 컴포넌트를 찾을 수 있을 것이다.
  
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.
+
아래에 있는 이 함수는 이미 파일에서 로드되거나 코드에서 생성된 XML 도큐먼드를 가져 올 것이며, 그 내용을 TreeView에 넣어 줄 것이다. 각 노드의 캡션은 각 노드의 첫번째 속성 값이 될 것이다.
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
 
procedure TForm1.XML2Tree(tree: TTreeView; XMLDoc: TXMLDocument);
 
var
 
var
Line 123: Line 134:
 
     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 143: Line 154:
 
   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;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
 
 
=== 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.
+
=== XML 도큐먼트 수정 하기===
 +
먼저, 기억할 것은 TDOMDocument 는 DOM에 대한 핸들이라는 것이다. XML 도큐먼트를 로딩하거나 TDOMDocument 를 한개 생성하여 이 클래스의 인스턴스를 얻을 수 있다.
  
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.
+
다른 한편으로 노드는 통상적인 객체처럼 생성될 수 없다. 생성하기 위해서는 *반드시* TDOMDocument에서 제공하는 메쏘드를 사용하여야 한다. 통상적인 객체는 트리상의 정확한 위치에 넣기 위해서 다른 메써드를 사용한다. 이는 노드는 DOM사의 특정한 도큐먼트에 의해 ''소유되어야''하기 때문이다.
  
Below are some common methods from TDOMDocument:
+
아래는 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 173:
 
     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 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]].
+
다음은 선택된 아이템을 TTreeView상에 위치시키고 자식 노드를 그것이 표현하는 XML 도큐먼트에 삽입하는 예제 메쏘드를 보여 줄 것이다. TreeView는 [[Networking#Populating a TreeView with XML|XML2Tree 함수]]를 사용하여 XML 파일의 내용으로 먼저 채워져 있어야 한다.
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
procedure TForm1.actAddChildNode(Sender: TObject);
 
procedure TForm1.actAddChildNode(Sender: TObject);
 
var
 
var
Line 174: Line 184:
 
begin
 
begin
 
   {*******************************************************************
 
   {*******************************************************************
   *  Detects the selected element
+
   *  선택된 원소를 찾고
 
   *******************************************************************}
 
   *******************************************************************}
 
   if TreeView1.Selected = nil then Exit;
 
   if TreeView1.Selected = nil then Exit;
Line 182: Line 192:
 
     position := TreeView1.Selected.Index;
 
     position := TreeView1.Selected.Index;
  
     NovoNo := XMLDoc.CreateElement('item');
+
     NovoNo := XMLDoc.CreateElement('아이템');
     TDOMElement(NovoNo).SetAttribute('nome', 'Item');
+
     TDOMElement(NovoNo).SetAttribute('이름', '아이템');
     TDOMElement(NovoNo).SetAttribute('arquivo', 'Arquivo');
+
     TDOMElement(NovoNo).SetAttribute('Heennavi', '흰나비');
 
     with XMLDoc.DocumentElement.ChildNodes do
 
     with XMLDoc.DocumentElement.ChildNodes do
 
     begin
 
     begin
Line 192: Line 202:
  
 
     {*******************************************************************
 
     {*******************************************************************
     *  Updates the TreeView
+
     *  TreeView를 업데이트하고
 
     *******************************************************************}
 
     *******************************************************************}
 
     TreeView1.Items.Clear;
 
     TreeView1.Items.Clear;
Line 200: Line 210:
 
   begin
 
   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;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
=== Create a TXMLDocument from a string ===
+
=== 문자열로 부터 TXMLDocument 생성 ===
  
Given al XML file in MyXmlString, the following code will create it's DOM:
+
MyXmlString에 있는 모든 XML 파일에서 다음 코드는 그것의 DOM을 생성할 것이다.
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
Var
 
Var
 
   S : TStringStream;
 
   S : TStringStream;
Line 221: Line 231:
 
     S.Position:=0;
 
     S.Position:=0;
 
     XML:=Nil;
 
     XML:=Nil;
     ReadXMLFile(XML,S); // Complete XML document
+
     ReadXMLFile(XML,S); // 완전한 XML 도큐먼트
     // Alternatively:
+
     //다른 방법으로는:
     ReadXMLFragment(AParentNode,S); // Read only XML fragment.
+
     ReadXMLFragment(AParentNode,S); // XML 조각들만 읽는다.
 
   Finally
 
   Finally
 
     S.Free;
 
     S.Free;
 
   end;
 
   end;
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
  
=== 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).
+
2007년 3월 이래, DTD 인증 도구가 FCL XML 파서에 추가 되었다.
 +
인증은 미리 정의된 규칙에 문서가 적합한지 문서의 논리적인 구조를 체크하는 것으로, ''Document Type Definition'' (DTD).이라고 부른다.
  
Here is an example of XML document with a DTD:
+
DTD를 이용한 XML 문서의 예가 있다:
  
<xml>
+
<syntaxhighlight lang="xml">
 
   <?xml version='1.0'?>
 
   <?xml version='1.0'?>
 
   <!DOCTYPE root [
 
   <!DOCTYPE root [
Line 246: Line 257:
 
     <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.
+
'root' 원소를 지정하는 이 DTD는 반드시 한개 또는 그 이상의 'child' 원소를 가져야 하며, 'child' 원소는 내부에 한개의 문자 데이터만 가질 수 있다. 만약 파서가 이 규칙에 위배되는 것을 탐지한면 이것을 보고할 것이다.
  
Loading such document is slightly more complicated. Let's assume we have XML data in a TStream object:
+
그런 문서를 로딩하는 것은 약간 복잡하다. TStream 객체에 있는 XML 데이터를 가지고 있다고 가정하자:
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
procedure TMyObject.DOMFromStream(AStream: TStream);
 
procedure TMyObject.DOMFromStream(AStream: TStream);
 
var
 
var
Line 259: Line 270:
 
   TheDoc: TXMLDocument;
 
   TheDoc: TXMLDocument;
 
begin
 
begin
   // create a parser object
+
   // 파서 객체 생성
 
   Parser := TDOMParser.Create;
 
   Parser := TDOMParser.Create;
   // and the input source
+
   // 그리고 입력 소스 생성
 
   Src := TXMLInputSource.Create(AStream);
 
   Src := TXMLInputSource.Create(AStream);
   // we want validation
+
   // 인증을 원하고
 
   Parser.Options.Validate := True;
 
   Parser.Options.Validate := True;
   // assign a error handler which will receive notifications
+
   // 통지를 받을 수있는 에러 핸들러를 할당
 
   Parser.OnError := @ErrorHandler;
 
   Parser.OnError := @ErrorHandler;
   // now do the job
+
   // 이제 작업을 수행
 
   Parser.Parse(Src, TheDoc);
 
   Parser.Parse(Src, TheDoc);
   // ...and cleanup
+
   // ...그리고 깨끗이 정리
 
   Src.Free;
 
   Src.Free;
 
   Parser.Free;
 
   Parser.Free;
Line 276: Line 287:
 
procedure TMyObject.ErrorHandler(E: EXMLReadError);
 
procedure TMyObject.ErrorHandler(E: EXMLReadError);
 
begin
 
begin
   if E.Severity = esError then  // we are interested in validation errors only
+
   if E.Severity = esError then  // 우리는 오직 인증 에러에 만 관심있다.
 
     writeln(E.Message);
 
     writeln(E.Message);
 
end;
 
end;
</delphi>
+
</syntaxhighlight>
 +
 
 +
=== 공백문자 ===
 +
만약 노드 텍스트에서 선행 공작 문자열을 보존하려면 XML 문서를 로드하는 위의 방법을 사용하면 된다. 선행 공백 문자열은 기본적으로 무시하도록 되어있다. 이것은 ReadXML(...)함수가 텍스트 노드에 있는 어떠한 선행 공백문자로 리턴하지 않기 때문이다.
 +
''Parser.Parse(Src, TheDoc)'' 를 호출하기 전에 다음 라인을 삽입한다
 +
 
 +
<syntaxhighlight lang=pascal>Parser.Options.PreserveWhitespace := True;</syntaxhighlight>
 +
 
 +
이렇게 하면 파서가 모든 공백 문자를 리턴하도록 한다. 이것은 XML 문서에 있는 모든 개행 문자를 포함하여 더 읽기 쉽도록 해준다.
  
=== Generating a XML file ===
+
=== XML 파일 생성===
  
Below is the complete code to write in a XML file.
+
XML 파일을 쓰는 완전한 코드가 아래에 있다.
(This was taken from a tutorial in DeveLazarus blog )
+
(DeveLazarus 블로그에 있는 튜토리얼에서 가져왔다)
Please, remember DOM and XMLWrite libs in uses clause
+
uses 절에 DOM XMLWrite 라이브러리가 있다는 것을 기억하시오
  
<delphi>
+
<syntaxhighlight lang=pascal>
 
unit Unit1;
 
unit Unit1;
  
Line 320: Line 339:
 
procedure TForm1.Button1Click(Sender: TObject);
 
procedure TForm1.Button1Click(Sender: TObject);
 
var
 
var
   xdoc: TXMLDocument;                                 // variable to document
+
   xdoc: TXMLDocument;                             // 문서에 대한 변수
   RootNode, parentNode, nofilho: TDOMNode;                   // variable to nodes
+
   RootNode, parentNode, nofilho: TDOMNode;       // 노드에 대한 변수
 
begin
 
begin
   //create a document
+
   // 문서 생성
 
   xdoc := TXMLDocument.create;
 
   xdoc := TXMLDocument.create;
  
   //create a root node
+
   // root 노드 생성
 
   RootNode := xdoc.CreateElement('register');
 
   RootNode := xdoc.CreateElement('register');
   Xdoc.Appendchild(RootNode);                           // save root node
+
   Xdoc.Appendchild(RootNode);                     // root 노드 저장
  
   //create a parent node
+
   // 부모 노드 생성
 
   RootNode:= xdoc.DocumentElement;
 
   RootNode:= xdoc.DocumentElement;
 
   parentNode := xdoc.CreateElement('usuario');
 
   parentNode := xdoc.CreateElement('usuario');
   TDOMElement(parentNode).SetAttribute('id', '001');       // create atributes to parent node
+
   TDOMElement(parentNode).SetAttribute('id', '001'); // 부모 노드에 대한 속성 생성
   RootNode.Appendchild(parentNode);                         // save parent node
+
   RootNode.Appendchild(parentNode);                   // 부모 노드 저장
  
   //create a child node
+
   // 자식 노드 생성
   parentNode := xdoc.CreateElement('nome');               // create a child node
+
   parentNode := xdoc.CreateElement('nome');           // 자식 노드 생성
   //TDOMElement(parentNode).SetAttribute('sexo', 'M');     // create atributes
+
   //TDOMElement(parentNode).SetAttribute('sexo', 'M');// 속성 생성
   nofilho := xdoc.CreateTextNode('Fernando');        // insert a value to node
+
   nofilho := xdoc.CreateTextNode('Fernando');        // 값을 노드에 삽입
   parentNode.Appendchild(nofilho);                         // save node
+
   parentNode.Appendchild(nofilho);                   // 노드 저장
   RootNode.ChildNodes.Item[0].AppendChild(parentNode);       // insert child node in respective parent node
+
   RootNode.ChildNodes.Item[0].AppendChild(parentNode);// 자식 노드를 해당하는 부모 노드에 삽입
  
   //create a child node
+
   // 자식 노드 생성
 
   parentNode := xdoc.CreateElement('idade');              // create a child node
 
   parentNode := xdoc.CreateElement('idade');              // create a child node
 
   //TDOMElement(parentNode).SetAttribute('ano', '1976');  // create atributes
 
   //TDOMElement(parentNode).SetAttribute('ano', '1976');  // create atributes
Line 358: Line 377:
  
 
end.
 
end.
</delphi>
+
</syntaxhighlight>
  
The  result will be the XML file below:
+
결과는 아래의 XML 파일이 될 것이다:
<xml>
+
<syntaxhighlight lang="xml">
 
<?xml version="1.0"?>
 
<?xml version="1.0"?>
 
<register>
 
<register>
Line 369: Line 388:
 
   </usuario>
 
   </usuario>
 
</register>
 
</register>
</xml>
+
</syntaxhighlight>
  
 
--[[User:Fernandosinesio|Fernandosinesio]] 22:28, 24 April 2008 (CEST)fernandosinesio@gmail.com
 
--[[User:Fernandosinesio|Fernandosinesio]] 22:28, 24 April 2008 (CEST)fernandosinesio@gmail.com
  
=== Encoding ===
+
=== 인코딩===
 +
 
 +
SVN 개정판 12582에서 시작하여 XML 리더는 외부 디코더를 사용한 어떠한 인코딩된 데이터라도 처리할 수 있다.
 +
 
 +
XML 표준에 의하면, XML의 첫번째 라인에 있는 인코딩 속성은 실제 코딩이 UTF-8 이나 UTF-16(BOM이 있으면 감지할 수 있다)인 경우에는 선택 사항이다. 0.9.26 버전 라자루스에서는,  TXMLDocument에 인코딩 속성이 있지만, 무시된다. writeXMLFile 은 항상 UTF-8을 이용하며 XML 파일의 첫 라인에 인코딩 속성을 생성하지 않는다.
  
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.
+
* [[XML Decoders|XML 디코더]]
 +
* [[Using INI Files|INI 파일의 사용]]
 +
* [[fcl-xml]]
 +
* [[Internet Tools|인터넷 도구]]
  
== External Links ==
+
== 외부 링크 ==
  
* [http://www.w3schools.com/xml/default.asp W3Schools] Xml Tutorial
+
* [http://www.w3schools.com/xml/default.asp W3Schools] Xml 튜토리얼
  
* [http://www.thomas-zastrow.de/texte/fpcxml/index.php Thomas Zastrow article] FPC and XML
+
* [http://www.thomas-zastrow.de/texte/fpcxml/index.php Thomas Zastrow 문서] FPC XML
  
[[Category:Free Component Library]]
 
  
 
----
 
----
[[Multithreaded Application Tutorial]]
+
[[Multithreaded Application Tutorial| 멀티 쓰레드 응용프로그램 튜토리얼]]

Latest revision as of 03:48, 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)

소개

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

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

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

유용한 예제

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

uses 절에 있는 유닛: Unicode 또는 Ansi

FPC는 ansi로 인코딩 된 루틴을 이용할 수 있는 XML 유닛을 포함하므로 각 플랫폼에의 인코딩은 달라질 수 있으며 Unicode가 아닐 수 있다. 라자루스는 LaxUtils 패키지에 모든 플랫폼에서 UTF-8 유니코드를 완전히 지원하는 각기 다른 XML 유닛의 서브셋을 가진다. 이 유닛은 상호 호환성이 있어 uses 절만 바꿈으로써 다른 것으로 바꿀 수 있다.

시스템 인코딩에서 인코딩 된 문자열을 사용하는 FPC XML 유닛은 다음과 같다: DOM, XMLRead, XMLWrite, XMLCfg, XMLUtils, XMLStreaming.

완전히 UTF-8 유니코드를 지원하는 라지루스 XML을 지원하는 유닛은 다음과 같다: laz2_DOM, laz2_XMLRead, laz2_XMLWrite, laz2_XMLCfg, laz2_XMLUtils, laz_XMLStreaming.

모든 예제에서 위의 모든 유닛을 포함하는 것은 아니다.

텍스트 노드 읽기

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

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

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

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

다음 코드는 텍스트 노드에서 값을 검색하는 경우의 올바른 방법과 틀린 방법을 보여 준다:

 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;

노드의 이름을 프린드 하기

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

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

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

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

 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;

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

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

TreeView 를 XML과 함께 넣기

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

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

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;

XML 도큐먼트 수정 하기

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

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

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

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

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;

문자열로 부터 TXMLDocument 생성

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

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;

문서 검증

2007년 3월 이래, DTD 인증 도구가 FCL XML 파서에 추가 되었다. 인증은 미리 정의된 규칙에 문서가 적합한지 문서의 논리적인 구조를 체크하는 것으로, Document Type Definition (DTD).이라고 부른다.

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>

'root' 원소를 지정하는 이 DTD는 반드시 한개 또는 그 이상의 'child' 원소를 가져야 하며, 그 'child' 원소는 내부에 한개의 문자 데이터만 가질 수 있다. 만약 파서가 이 규칙에 위배되는 것을 탐지한면 이것을 보고할 것이다.

그런 문서를 로딩하는 것은 약간 복잡하다. TStream 객체에 있는 XML 데이터를 가지고 있다고 가정하자:

procedure TMyObject.DOMFromStream(AStream: TStream);
var
  Parser: TDOMParser;
  Src: TXMLInputSource;
  TheDoc: TXMLDocument;
begin
  // 파서 객체 생성
  Parser := TDOMParser.Create;
  // 그리고 입력 소스 생성
  Src := TXMLInputSource.Create(AStream);
  // 인증을 원하고
  Parser.Options.Validate := True;
  // 통지를 받을 수있는 에러 핸들러를 할당
  Parser.OnError := @ErrorHandler;
  // 이제 작업을 수행
  Parser.Parse(Src, TheDoc);
  // ...그리고 깨끗이 정리
  Src.Free;
  Parser.Free;
end;

procedure TMyObject.ErrorHandler(E: EXMLReadError);
begin
  if E.Severity = esError then  // 우리는 오직 인증 에러에 만 관심있다.
    writeln(E.Message);
end;

공백문자

만약 노드 텍스트에서 선행 공작 문자열을 보존하려면 XML 문서를 로드하는 위의 방법을 사용하면 된다. 선행 공백 문자열은 기본적으로 무시하도록 되어있다. 이것은 ReadXML(...)함수가 텍스트 노드에 있는 어떠한 선행 공백문자로 리턴하지 않기 때문이다. Parser.Parse(Src, TheDoc) 를 호출하기 전에 다음 라인을 삽입한다

Parser.Options.PreserveWhitespace := True;

이렇게 하면 파서가 모든 공백 문자를 리턴하도록 한다. 이것은 XML 문서에 있는 모든 개행 문자를 포함하여 더 읽기 쉽도록 해준다.

XML 파일 생성

XML 파일을 쓰는 완전한 코드가 아래에 있다. (DeveLazarus 블로그에 있는 튜토리얼에서 가져왔다) uses 절에 DOM 과 XMLWrite 라이브러리가 있다는 것을 기억하시오

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;                             // 문서에 대한 변수
  RootNode, parentNode, nofilho: TDOMNode;        // 노드에 대한 변수
begin
  // 문서 생성
  xdoc := TXMLDocument.create;

  // root 노드 생성
  RootNode := xdoc.CreateElement('register');
  Xdoc.Appendchild(RootNode);                     // root 노드 저장

  // 부모 노드 생성
  RootNode:= xdoc.DocumentElement;
  parentNode := xdoc.CreateElement('usuario');
  TDOMElement(parentNode).SetAttribute('id', '001');  // 부모 노드에 대한 속성 생성
  RootNode.Appendchild(parentNode);                   // 부모 노드 저장

  // 자식 노드 생성
  parentNode := xdoc.CreateElement('nome');           // 자식 노드 생성
  //TDOMElement(parentNode).SetAttribute('sexo', 'M');// 속성 생성
  nofilho := xdoc.CreateTextNode('Fernando');         // 값을 노드에 삽입
  parentNode.Appendchild(nofilho);                    // 노드 저장
  RootNode.ChildNodes.Item[0].AppendChild(parentNode);// 자식 노드를 해당하는 부모 노드에 삽입

  // 자식 노드 생성
  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.

결과는 아래의 XML 파일이 될 것이다:

<?xml version="1.0"?>
<register>
  <usuario id="001">
    <nome>Fernando</nome>
    <idade>32</idade>
  </usuario>
</register>

--Fernandosinesio 22:28, 24 April 2008 (CEST)fernandosinesio@gmail.com

인코딩

SVN 개정판 12582에서 시작하여 XML 리더는 외부 디코더를 사용한 어떠한 인코딩된 데이터라도 처리할 수 있다.

XML 표준에 의하면, XML의 첫번째 라인에 있는 인코딩 속성은 실제 코딩이 UTF-8 이나 UTF-16(BOM이 있으면 감지할 수 있다)인 경우에는 선택 사항이다. 0.9.26 버전 라자루스에서는, TXMLDocument에 인코딩 속성이 있지만, 무시된다. writeXMLFile 은 항상 UTF-8을 이용하며 XML 파일의 첫 라인에 인코딩 속성을 생성하지 않는다.

더 볼 것

외부 링크



멀티 쓰레드 응용프로그램 튜토리얼