根据下面的XML代码段,如何获取XML属性TEXT
的值?
<POPULARITY URL="example.com" SOURCE="panel" TEXT="27503270" />
否定...
我的代码......:
procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
if kontrol=0 then
begin
XMLDocument1.Active:=false;
XMLDocument1.FileName:='http://data.alexa.com/data?cli=10&dat=snbamz&url=aliatabak.com';
XMLDocument1.Active:=true;
end;
i:=1;
baslangic:=XMLDocument1.DocumentElement.ChildNodes.FindNode('SD');
repeat
isim:=baslangic.ChildNodes.Nodes['??????'].Text;
edit1.Text:=isim;
i:=i+1;
baslangic:=baslangic.NextSibling;
Until baslangic=nil;
end;
答案 0 :(得分:10)
使用IXMLNode.Attributes
属性:
isim := VarToStr(baslangic.Attributes['TEXT']);
或IXMLNode.AttributeNodes
属性:
Isim := baslangic.AttributeNodes.Nodes['TEXT'].Text;
或者:
Attr := baslangic.AttributeNodes.FindNode('TEXT');
If Attr <> nil then
isim := Attr.Text;
答案 1 :(得分:4)
您可以使用XPath来检索值
试试这个示例应用
{$APPTYPE CONSOLE}
{$R *.res}
uses
MSXML,
SysUtils,
ActiveX,
ComObj,
Variants;
procedure GetInfoXML;
const
URI='http://data.alexa.com/data?cli=10&dat=snbamz&url=aliatabak.com';
OK =200;
COMPLETED=4;
var
XMLHTTPRequest : IXMLHTTPRequest;
XMLDOMDocument : IXMLDOMDocument;
XMLDOMNode : IXMLDOMNode;
begin
XMLHTTPRequest := CreateOleObject('MSXML2.XMLHTTP') As IXMLHTTPRequest;
try
XMLHTTPRequest.open('GET', URI, False, EmptyParam, EmptyParam);
XMLHTTPRequest.send('');
if (XMLHTTPRequest.readyState = COMPLETED) and (XMLHTTPRequest.status = OK) then
begin
XMLDOMDocument := XMLHTTPRequest.responseXML As IXMLDOMDocument2;
//get the node
XMLDOMNode := XMLDOMDocument.selectSingleNode('//ALEXA/SD/POPULARITY');
//get the "TEXT" attribute
Writeln(Format('%s',[String(XMLDOMNode.attributes.getNamedItem('TEXT').Text)]));
end;
finally
XMLHTTPRequest := nil;
end;
end;
begin
try
CoInitialize(nil);
try
GetInfoXML;
finally
CoUninitialize;
end;
except
on E:EOleException do
Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
答案 2 :(得分:2)
您可以使用XMLDataBinding(File / New / Othe / XML / XMLDataBinding)将XML转换为Delphi类,选择“Alexa.XML”文件。 Delphi将生成一个文件(例如Alexa.pas),其中包含用于处理XML数据的接口和类。
将XML映射到Delphi类,您可以轻松浏览XML数据。
示例:
function TYourClass.GetAlexaText(const FileName: string): string;
var
XMLDoc1: TXMLDocument;
Alexa: IXMLALEXAType;
begin
XMLDoc1 := TXMLDocument.Create(Self);
XMLDoc1.FileName := FileName;
XMLDoc1.Active := True;
Alexa := GetAlexa(XMLDoc1);
Result := IntToStr(Alexa.SD[1].POPULARITY.TEXT);
end;
希望这能帮到你!
答案 3 :(得分:1)
isim:=baslangic.ChildNodes['POPULARITY'].AttributeNodes['TEXT'].text;
我找到了..谢谢。