基于多个属性从XML读取

时间:2012-04-12 06:48:49

标签: xml delphi delphi-2010

我有以下格式的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属性组合的金额?

例如,我需要获得AmountID=225帐户的City=London。如果我使用像

这样的代码
Node.GetAttribute('ID')=225

它总是给我第一个ID = 225

的节点

感谢你。

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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;