Pradeep
Pradeep

Reputation: 309

Reading from XML based on multiple attributes

I have an XML in the following format:

<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>

Here, what makes an account unique is the combination of attributes ID and City.

How do I read the Amount uniquely? How do I read amount for a combination of ID and City attributes?

For example, I need to get the Amount for the account with ID=225 and City=London. If I use code like

Node.GetAttribute('ID')=225

it always gives me the first node with ID=225

Thanking you.

Upvotes: 4

Views: 3294

Answers (2)

SimaWB
SimaWB

Reputation: 9294

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;

Upvotes: 0

RRUZ
RRUZ

Reputation: 136431

Try with XPath, using this sentence ./Accounts/Account[@ID="225"][@City="London"] to locate the node.

Try this sample

{$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.

Upvotes: 12

Related Questions