going through a XML file with Delphi and NativeXML:

1.7k views Asked by At

let's say that I've a XML file looking like this

<NOTE>
   <TO>
      <CONTACT>
         <NAME>Tove</NAME>
         <EMAIL>[email protected]</EMAIL>
      </CONTACT>
      <CONTACT>
         <NAME>Biggles</NAME>
         <EMAIL>[email protected]</EMAIL>
      </CONTACT>
   </TO>
   <FROM>
      <CONTACT>
         <NAME>Jani</NAME>
         <EMAIL>[email protected]</EMAIL>
      </CONTACT>
   </FROM>
   <HEADING>Reminder</HEADING>
   <BODY>Party this weekend!</BODY>
</NOTE>

with NativeXML (at least until version 3.06) and this code

procedure TForm1.btnLoad1st2ndClick(Sender: TObject);
// Load an XML document and show the nodes present by enumerating them. Here
// we do only levels 1 and 2. An iterative approach could show all levels deep
var
  i, j: integer;
  NodeLevel1, NodeLevel2: TXmlNode;
begin
  // Clear the memo and create instance
  Memo1.Lines.Clear;
  FXml.Clear;
  // Load the XML file
  FXml.LoadFromFile(edXmlFileOpen.Text);
  // The Root property contains the root node, we use it as a base
  if assigned(FXml.Root) then
  begin
    // Iterate through all the child nodes of Root (level 1)
    for i := 0 to FXml.Root.NodeCount - 1 do
    begin
      NodeLevel1 := FXml.Root.Nodes[i];
      // Add the name of each child to the memo
      Memo1.Lines.Add(string(NodeLevel1.Name));
      // Also iterate through the grandchilds (level 2)
      for j := 0 to NodeLevel1.NodeCount - 1 do
      begin
        NodeLevel2 := NodeLevel1.Nodes[j];
        // Add these names too, with an indent
        Memo1.Lines.Add(' ' + string(NodeLevel2.Name));
      end;
    end;
  end;
end;

I get this response

TO
 CONTACT
 CONTACT
FROM
 CONTACT
HEADING
BODY

which is what I expected

but now I use NativeXML in version 4.07 and, with the same code, the result is

WhiteSpace
TO
 WhiteSpace
 CONTACT
 WhiteSpace
 CONTACT
 WhiteSpace
WhiteSpace
FROM
 WhiteSpace
 CONTACT
 WhiteSpace
WhiteSpace
HEADING
 CharData
WhiteSpace
BODY
 CharData
WhiteSpace

You guess that in real life, the XML will be a little bit more complicated. Is there a way to get, as simply as possible, the same result with the current version of NativeXML then before?

Thanks for your help

PS: by the way, I've take a look at this post "How do I iterate through similar nodes in an XML document using NativeXML in Delphi?" but the first proposed solution, which is similar to my sample, doesn't work. And the second one implies to use a list of nodes, what I would like to avoid.

1

There are 1 answers

0
teran On BEST ANSWER

you should simply use xml.root.ElementCount and xml.root.Elements[i] properties instead of NodeCount & Nodes[] (the same with nodelevel1.) to achieve desired ouput