程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi 中的 XMLDocument 類詳解(13) - 關於 XML 屬性

Delphi 中的 XMLDocument 類詳解(13) - 關於 XML 屬性

編輯:Delphi

unit Unit1; 
 
interface 
 
uses 
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
 Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, StdCtrls; 
 
type 
 TForm1 = class(TForm) 
  XMLDocument1: TXMLDocument; 
  Memo1: TMemo; 
  Button1: TButton; 
  Button2: TButton; 
  Button3: TButton; 
  Button4: TButton; 
  Button5: TButton; 
  procedure FormCreate(Sender: TObject); 
  procedure Button1Click(Sender: TObject); 
  procedure Button2Click(Sender: TObject); 
  procedure Button3Click(Sender: TObject); 
  procedure Button4Click(Sender: TObject); 
  procedure Button5Click(Sender: TObject); 
 end; 
 
var 
 Form1: TForm1; 
 
implementation 
 
{$R *.dfm} 
 
//打開 
procedure TForm1.FormCreate(Sender: TObject); 
begin 
 XMLDocument1.LoadFromFile('c:\temp\test.XML'); 
 {必須用萬一提供的 XML 測試文件, 才能有相同的返回值} 
end; 
 
 
//XMLDocument1 對象的 XML 屬性 
procedure TForm1.Button1Click(Sender: TObject); 
begin 
 {前面我們經常用這句話, 因為這裡的 Lines 與 XML 同屬於 TStrings} 
 Memo1.Lines := XMLDocument1.XML; 
 
 {如果不怕麻煩, 這樣寫也可以:} 
 Memo1.Lines.Text := XMLDocument1.XML.Text; 
 
 {如果知道了這一點, 那 XML 屬性的功能可就多了, 並且這裡的 XML 屬性是可寫的} 
 {不過這裡要談的是節點的 XML 屬性} 
end; 
 
 
//根節點的 XML 屬性 
procedure TForm1.Button2Click(Sender: TObject); 
var 
 node: IXMLNode; 
begin 
 {先看根節點: XMLDocument1.DocumentElement} 
 node := XMLDocument1.DocumentElement; 
 
 //Memo1.Lines := node.XML; {這一句會出錯} 
 {因為節點的 XML 屬性是 WideString 類型的, 應該這樣:} 
 Memo1.Lines.Text := node.XML; {將會讀出根節點與根節點包含的所有內容} 
 
 {還有一個更大的區別: 節點的 XML 是只讀的!} 
end; 
 
 
//子節點的 XML 屬性 
procedure TForm1.Button3Click(Sender: TObject); 
var 
 node: IXMLNode; 
begin 
 node := XMLDocument1.DocumentElement; 
 node := node.ChildNodes[0]; 
 
 Memo1.Lines.Text := node.XML; {會顯示一個子節點的全部} 
end; 
 
 
//屬性的 XML 屬性 
procedure TForm1.Button4Click(Sender: TObject); 
var 
 node: IXMLNode; 
begin 
 node := XMLDocument1.DocumentElement; 
 node := node.AttributeNodes[0]; {屬性也是 IXMLNode 類型的} 
 
 ShowMessage(node.NodeName); {備注} 
 ShowMessage(node.NodeValue); {測試} 
 
 {用 XML 屬性一次把他們都讀出來:} 
 ShowMessage(node.XML);    {備注="測試"} 
end; 
 
 
//葉節點的 XML 屬性 
procedure TForm1.Button5Click(Sender: TObject); 
var 
 node: IXMLNode; 
begin 
 node := XMLDocument1.DocumentElement; 
 node := node.ChildNodes[0]; 
 node := node.ChildNodes[0]; 
 node := node.ChildNodes[0]; {這就是葉節點了} 
 
 ShowMessage(node.XML); {張三} 
 
 {這時的 XML 屬性和 Text 屬性一樣了} 
 ShowMessage(node.Text); {張三} 
end; 
 
end. 


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved