2009年5月29日

Delphi MSXML DOM XPath


{
XPath 參考網頁
http://www.w3.org/TR/xpath
在 uses 中加入 msxml, msxmldom
}
uses
msxml, msxmldom;
{
在 Form 上放一個 TMemo
在 FormCreate 事件中加入
}

procedure TForm1.FormCreate(Sender: TObject);
var
DOMDocument: IXMLDOMDocument;
begin
with memo1.Lines do
begin
Clear;
Add('<?xml version="1.0" encoding="Big5"?>');
Add('<html lang="en">');
Add(' <head>');
Add(' <title>Extensible Markup Language (XML)</title>');
Add(' </head>');
Add(' <body>');
Add(' <a href="1">first</a>');
Add(' <a href="2">second</a>');
Add(' </body>');
Add('</html>');
end;

DOMDocument := CreateDOMDocument;
DOMDocument.loadXML(memo1.Lines.Text);

with DOMDocument, Memo1.Lines do
begin
Clear;
Values['title'] := selectSingleNode('/html/head/title/text()').nodeValue;
Values['All Tag Count'] := IntToStr(selectNodes('//*').length);
Values['body Tag child Nodes Count'] := IntToStr(selectNodes('/*/body/*').length);
Values['a Tag Count'] := IntToStr(selectNodes('//a').length);
Values['First a Tag Text'] := selectSingleNode('//a[1]/text()').nodeValue;
Values['First a Tag href'] := selectSingleNode('//a[1]/@href').nodeValue;
Values['href equal 2 Text'] := selectSingleNode('//a[@href=2]/text()').nodeValue;
end;
end;
{
title=Extensible Markup Language (XML)
All Tag Count=6
body Tag child Nodes Count=2
a Tag Count=2
First a Tag Text=first
First a Tag href=1
href equal 2 Text=second
}

沒有留言:

網誌存檔