Miguel E
Miguel E

Reputation: 1326

Extract values inside XML

I need to parse the following XML:

<?xml version="1.0" encoding="UTF-8" ?>
<revista numero="2226" data="03/09/2013">
  <processo numero="902987089">
    <despachos>
      <despacho codigo="IPAS139"/>
    </despachos>
    <titulares>
      <titular nome-razao-social="AAAAA" pais="BR" uf="PR"/>
    </titulares>
  </processo>
  <processo numero="902812165">
    <despachos>
      <despacho codigo="IPAS029"/>
    </despachos>
    <titulares>
      <titular nome-razao-social="XXXX" pais="BR" uf="SC"/>
    </titulares>
(...)

I'm not experienced at all with XML. I'm using IXMLDocument in Delphi.

LNodeElement := LDocument.ChildNodes.FindNode('revista');
(...)
for I := 0 to LNodeElement.ChildNodes.Count - 1 do
(...)

My question is how can I reach the numero attribute value inside the <processo> tag? But if a kind soul could share a small example it would be most appreciated.

Upvotes: 3

Views: 2019

Answers (1)

TLama
TLama

Reputation: 76663

For instance this way:

uses
  XMLDoc, XMLIntf;

procedure TForm3.Button1Click(Sender: TObject);
var
  I: Integer;
  NumberAttr: IXMLNode;
  XMLDocument: IXMLDocument;
  ProcessNodes: IXMLNodeList;
begin
  // load an XML file
  XMLDocument := LoadXMLDocument('c:\File.xml');
  // take the list of all "revista/processo" nodes
  ProcessNodes := XMLDocument.DocumentElement.ChildNodes;
  // and iterate that "processo" node collection
  for I := 0 to ProcessNodes.Count - 1 do
  begin
    // try to find the "numero" attribute for currently iterated "processo" node
    NumberAttr := ProcessNodes[I].AttributeNodes.FindNode('numero');
    // if the "numero" attribute was found, show its value (or do something else)
    if Assigned(NumberAttr) then
      ShowMessage(NumberAttr.Text);
  end;
end;

Upvotes: 5

Related Questions