Gary
Gary

Reputation: 23

Delphi XML - obtaining a value from parent node

I am new to using XML in Delphi, and have used the questions already posted to find out most of what I need to know (thank you!). However ... I am struggling to obtain a data value from the top of the XML file issued by one of our suppliers.

The top of the XML file is shown below:

<?xml version="1.0" encoding="utf-8"?>
<form billId="1004" penId="ABCDE" appName="Report Sheet" penSerialNo="AJX-AAT-AGK-B4" >
<question id="1" reference="site_name" value="Acme Inc" /></question>
<question id="2" reference="site_address" value="London" /></question>
<question id="3" reference="TQM_job_no" value="AB1234567" /></question>
<question id="4" reference="TQM_site_no" value="XX999" /></question>

How can I obtain the penId and penSerialNo values?

For reference, I am using the code below, obtained from another post on the site, to traverse the XML and obtain the values from the question nodes:

for i:= 0 to XMLDocument1.DocumentElement.ChildNodes.Count - 1 do
   begin
       Node:= XMLDocument1.DocumentElement.ChildNodes[I];
 if Node.NodeName = 'question' then
  begin
   if Node.HasAttribute('value') then
    VALUEvar:= Node.Attributes[value'];
    // do something with VALUEvar which is a string
      end;
end;
end;

I would really appreciate any help that could be provided ... thanks in advance!

Upvotes: 2

Views: 3216

Answers (1)

TLama
TLama

Reputation: 76733

Since form is your root node, you can use something like this:

uses
  XMLDoc, XMLIntf;

procedure TForm1.Button1Click(Sender: TObject);
var
  XMLDocument: IXMLDocument;
begin
  XMLDocument := LoadXMLDocument('c:\YourFile.xml');
  if XMLDocument.DocumentElement.HasAttribute('penId') then
    ShowMessage(VarToStr(XMLDocument.DocumentElement.Attributes['penId']));
  if XMLDocument.DocumentElement.HasAttribute('penSerialNo') then
    ShowMessage(VarToStr(XMLDocument.DocumentElement.Attributes['penSerialNo']));
end;

Anyway, your document is invalid. You cannot use tags enclosed like:

<tag attr="value"/></tag>

Either use:

<tag attr="value"/>

or

<tag attr="value"></tag>

Upvotes: 3

Related Questions