Delphi 中的 XMLDocument 類詳解(14) – 遍曆 XML 檔案

來源:互聯網
上載者:User
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, StdCtrls;type  TForm1 = class(TForm)    XMLDocument1: TXMLDocument;    Button1: TButton;    Button2: TButton;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  end;var  Form1: TForm1;implementation{$R *.dfm}//讀取 xml 的函數{  功能1: 傳入一個節點參數, 返回節點及其包含的所有內容;  功能2: 排除了空節點.}function ReadXml(node: IXMLNode): string;var  nodeList,attrList: IXMLNodeList;  str,strName,strValue: string;  i: Integer;begin  Result := '';  if not node.HasChildNodes then Exit;  attrList := node.AttributeNodes;      {根節點的屬性列表}  nodeList := node.ChildNodes;          {根節點下的子節點列表}  str := '<' + node.NodeName;  {先讀取屬性}  for i := 0 to attrList.Count - 1 do  begin    strName := attrList[i].NodeName;    strValue := attrList[i].NodeValue;    str := str + ' ' + strName + '=' + AnsiQuotedStr(strValue, '"');  end;  str := str + '>' + sLineBreak; {sLineBreak 是常量, 相當於 #13#10}  {讀取子節點}  for i := 0 to nodeList.Count - 1 do  begin    strName := nodeList[i].NodeName;    if nodeList[i].IsTextElement then    begin      strValue := nodeList[i].NodeValue;      str := str + '<' + strName + '>' + strValue + '</' + strName + '>' + sLineBreak;    end else if nodeList[i].HasChildNodes then    begin      str := str + ReadXml(nodeList[i]);               {這是最關鍵的遞迴調用}      str := str + '</' + strName + '>' + sLineBreak;  {封口}    end;  end;  str := str + '</' + node.NodeName + '>'; {封口}  Result := str;end;//調用測試(1):procedure TForm1.Button1Click(Sender: TObject);var  str,s1,s2: string;begin  XMLDocument1.LoadFromFile('c:\temp\test.xml');  {必須用萬一提供的 xml 測試檔案, 才能有相同的傳回值}  {讀取檔案頭}  s1 := AnsiQuotedStr(XMLDocument1.Version, '"');  {讀出版本, 並添加雙引號}  s2 := AnsiQuotedStr(XMLDocument1.Encoding, '"'); {讀出字元集, 並添加雙引號}  str := Format('<?xml version=%s encoding=%s?>',[s1,s2]); {這就是檔案頭了}  str := str + sLineBreak + ReadXml(XMLDocument1.DocumentElement);  ShowMessage(str); {返回 xml 包含問頭在內的所有內容}end;//調用測試(2)procedure TForm1.Button2Click(Sender: TObject);var  str: string;  node: IXMLNode;begin  XMLDocument1.LoadFromFile('c:\temp\test.xml');  node := XMLDocument1.DocumentElement.ChildNodes[0];  str := ReadXml(node);  ShowMessage(str); {返回返回根節點下第一個子節點的所有內容}end;end.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.