2012-04-12 87 views
4

我有以下格式的XML:基於多個XML閱讀屬性

<Accounts> 
    <Account ID="1" City="Bangalore" Amount="2827561.95" /> 
    <Account ID="225" City="New York" Amount="12312.00" /> 
    <Account ID="236" City="London" Amount="457656.00" /> 
    <Account ID="225" City="London" Amount="23462.40" /> 
    <Account ID="236" City="Bangalore" Amount="2345345.00" /> 
</Accounts> 

這裏,是什麼讓一個帳戶的獨特屬性是和IDCity組合。

如何唯一讀取Amount?如何讀取IDCity屬性組合的金額?

例如,我需要爲ID=225City=London帳戶獲取Amount。如果我使用如下代碼

Node.GetAttribute('ID')=225 

它總是給我ID的第一個節點= 225

感謝你。

+1

如何使用'Node.GetAttribute( 'ID')= 225'?你是用循環還是...? – 2012-04-12 07:00:01

+0

是的,我在循環中使用它。像... Node:= rootNode.ChildNodes.FindNode('Accounts'); for i:= 0 to Node.ChildNodes.Count - 1 do begin childnode:= Node.ChildNodes [i]; if Node.HasAttribute('ID')then amount:= Node.GetAttribute('ID'); ...... .. – Pradeep 2012-04-12 10:15:44

+0

然後你可以在if語句中添加第二個條件來比較'City'的內容。 – 2012-04-12 10:26:54

回答

12

嘗試使用XPath,使用此句子./Accounts/Account[@ID="225"][@City="London"]來定位節點。

試試這個樣本

{$APPTYPE CONSOLE} 

uses 
    MSXML, 
    SysUtils, 
    ActiveX, 
    ComObj; 

Const 
XmlStr = 
' <Accounts>'+ 
' <Account ID ="1" City="Bangalore" Amount="2827561.95"/>'+ 
' <Account ID="225" City="New York" Amount="12312.00"/>'+ 
' <Account ID="236" City="London" Amount="457656.00"/>'+ 
' <Account ID="225" City="London" Amount="23462.40"/>'+ 
' <Account ID="236" City="Bangalore" Amount="2345345.00"/>'+ 
'</Accounts>'; 

procedure Test; 
Var 
    XMLDOMDocument : IXMLDOMDocument; 
    XMLDOMNode  : IXMLDOMNode; 
begin 
    XMLDOMDocument:=CoDOMDocument.Create; 
    XMLDOMDocument.loadXML(XmlStr); 
    XMLDOMNode := XMLDOMDocument.selectSingleNode(Format('./Accounts/Account[@ID="%s"][@City="%s"]', ['225', 'London'])); 
    if XMLDOMNode<>nil then 
    Writeln(Format('Amount %s',[String(XMLDOMNode.attributes.getNamedItem('Amount').Text)])); 
end; 

begin 
try 
    CoInitialize(nil); 
    try 
     Test; 
    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. 
+3

+1。你也可以使用XPath:'/ Accounts/Account [@ID =「%s」和@City =「%s」]' – kobik 2012-04-12 07:39:46

0
function getAmount(Id, City: string): string; 
begin 
    Result := '' 
    aNode := xmldocument1.DocumentElement.ChildNodes['Accounts']; 
    for i := 0 to ChildNodes.Count do 
    with aNode.Nodes[i] do 
     if (Attributes['ID'] = Id) and (Attributes['City'] = City) then 
     begin 
     Result:= Attributes['Amount']; 
     Break; 
     end; 
    end; 
end;