AdaPower Logged in as Guest
Ada Tools and Resources

Ada 95 Reference Manual
Ada Source Code Treasury
Bindings and Packages
Ada FAQ


Join >
Home >
Articles >
Getting Started >
Ada FAQ >
Source Treasury >
Books & Tutorials >
Packages for Reuse >
Latest Additions >
Ada Projects >
Press Releases >
Ada Audio / Video >
Home Pages >
Links >
Contact >
About >
Login >
Back
Basic XML Walk (David Botton)

Given an XML file called test.xml, the following example will walk the XML using XML/Ada:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed;

with Input_Sources.File;

with DOM.Readers;
with DOM.Core;

with DOM.Core.Documents;
with DOM.Core.Nodes;

procedure XML1 is

   L : Natural := 1;

   F : Input_Sources.File.File_Input;
   T : DOM.Readers.Tree_Reader;

   procedure Walk_Siblings (N : DOM.Core.Node);
   --  Walk through siblings

   procedure Walk_Children (N : DOM.Core.Node);
   --  Walk through children

   procedure Display_Node (N : DOM.Core.Node);
   --  Display node

   procedure Walk_Siblings (N : DOM.Core.Node) is
      use DOM.Core;
      NW : Node := N;
   begin
      while NW /= null loop
         Display_Node (NW);
         Walk_Children (NW);
         NW := Nodes.Next_Sibling (NW);
      end loop;
   end Walk_Siblings;

   procedure Walk_Children (N : DOM.Core.Node) is
      use DOM.Core;
      NW : Node := Nodes.First_Child (N);
   begin
      L := L + 1;

      if NW /= null then
         Display_Node (NW);
         Walk_Siblings (NW);
      end if;

      L := L - 1;
   end Walk_Children;

   procedure Display_Node (N : DOM.Core.Node) is
      use DOM.Core;
      use Ada.Strings.Fixed;
   begin
      if N /= null then
         if N.Node_Type = Element_Node then
            Put (L * "-->");
            Put_Line (Nodes.Node_Name (N));

            declare
               AS : Named_Node_Map := Nodes.Attributes (N);
            begin
               for I in 0 .. Nodes.Length (AS) loop
                  Display_Node (Nodes.Item (AS, I));
               end loop;
            end;

         elsif N.Node_Type = Attribute_Node then
            Put (L * "-->");
            Put_Line (Nodes.Node_Name (N) & " := " & Nodes.Node_Value (N));
         end if;
      end if;
   end Display_Node;

begin
   Input_Sources.File.Open ("test.xml", F);
   DOM.Readers.Parse (T, F);

   declare
      use DOM.Core;

      D : Document := DOM.Readers.Get_Tree (T);

      Root : Element := Documents.Get_Element (D);
   begin
      Walk_Siblings (Root);
   end;

   DOM.Readers.Free (T);
   Input_Sources.File.Close (F);
end XML1;


(c) 1998-2004 All Rights Reserved David Botton