D O M Recursive

ROOT implementation of a XML DOM Parser

This is an example of how Dom Parser walks the DOM tree recursively. This example will parse any xml file.

To run this program

.x DOMRecursive.C+

Requires: person.xml

Author: Sergey Linev
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Tuesday, June 22, 2021 at 10:19 AM.

In [1]:
%%cpp -d
#include <Riostream.h>
#include <TDOMParser.h>
#include <TXMLNode.h>
#include <TXMLAttr.h>
#include <TList.h>

A helper function is created:

In [2]:
%%cpp -d
void ParseContext(TXMLNode *node)
{
   for ( ; node; node = node->GetNextNode()) {
      if (node->GetNodeType() == TXMLNode::kXMLElementNode) { // Element Node
         cout << node->GetNodeName() << ": ";
         if (node->HasAttributes()) {
            TList* attrList = node->GetAttributes();
            TIter next(attrList);
            TXMLAttr *attr;
            while ((attr =(TXMLAttr*)next())) {
               cout << attr->GetName() << ":" << attr->GetValue();
            }
         }
     }
     if (node->GetNodeType() == TXMLNode::kXMLTextNode) { // Text node
        cout << node->GetContent();
     }
     if (node->GetNodeType() == TXMLNode::kXMLCommentNode) { //Comment node
        cout << "Comment: " << node->GetContent();
     }

     ParseContext(node->GetChildren());
   }
}
In [3]:
TDOMParser *domParser = new TDOMParser();
  TString dir = gROOT->GetTutorialDir();
  domParser->SetValidate(false); // do not validate with DTD
  domParser->ParseFile(dir+"/xml/person.xml");

  TXMLNode *node = domParser->GetXMLDocument()->GetRootNode();

  ParseContext(node);
PersonList: 
Comment: 
  This is an example...

Person: ID:1
    FirstName: Alicia
    LastName: Smith
    Gender: F
    DateOfBirth: 
        Day: 13
        Month: 10
        Year: 1978
    
    Address: 
        Street: Grand Avenue, 143
        PostalCode: Toronto 2283
        Country: Canada
    
  
  Person: ID:2
    FirstName: Maria
    LastName: White
    Gender: F
    DateOfBirth: 
        Day: 29
        Month: 5
        Year: 1980
    
    Address: 
        Street: Green Land Park, 143
        PostalCode: Vancouver BC V6C 2C2
        Country: Canada