Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Reusable Design and Code: DOM Walkers

One of the main techniques for DOM programming is the use of Visitors (also known as Walkers), which iterate through the document, as a collection of DOM nodes, performing a particular manipulation.

Figure 1 shows the structure of our Walker classes, as implemented in the following examples.

Figure 1 DOMWalker Class Diagram

Most of the aspects about Walkers are instances of reusable design as much as they are of reusable code. After all, a DOM Walker will always perform the following implementable actions:

Check the current node for its type, and decide what to do accordingly

  • Decide whether it wants to continue exploring the tree

  • Decide and implement how to explore the tree (implement a particular form of traversal: preorder, inorder, postorder, and so on)

Also, for each Walker (I use the terms Walker and Visitor interchangeably in this section), there is a client, supplying the DOM node from which the traversal begins. This client must be implemented repeatedly every time a Walker is constructed in order to do unit tests.

By this time, you no doubt have guessed the nature of our next Framework: the automatic creation of DOM Walkers using MSXML3.

A Particular Walker: BlockWorldRenderer

Before jumping into the creation of the Framework (implemented as a Visual Studio Project Wizard), take a look at an example of the type of application you want to generate.

Listing 1 shows the DTD for defining 3D figures in a world made of blocks. A block is identified by its position (three integers, one for each coordinate) and a color. Groups of blocks can be rotated arbitrarily, encapsulating them in a rotation element.

Your 3D worlds may also have additional information regarding the author of the model, and other additional data that will be ignored by the rendering engine. (You will create a DOM Walker named BlockWorldRenderer.)

Listing 1: BlockWorld.dtd

<!ELEMENT blockworld (head?,world)>
<!ELEMENT head    (author?,name,version?)>
<!ELEMENT author   (#PCDATA)>
<!ELEMENT name    (#PCDATA)>
<!ELEMENT version  EMPTY>
<!ATTLIST version  
     release  CDATA   #REQUIRED
     build   CDATA   #REQUIRED>
<!ELEMENT world    (rotation|block)*>
<!ENTITY % color   
"white|red|blue|green|purple|black">
<!ELEMENT block    EMPTY>
<!ATTLIST block
     x     CDATA   #REQUIRED
     y     CDATA   #REQUIRED
     z     CDATA   #REQUIRED
     color   (%color;) #REQUIRED>
<!ELEMENT rotation  (rotation|block)*>
<!ATTLIST rotation
     angle   CDATA   #REQUIRED
     axis    (x|y|z)  #REQUIRED>

A simple blockworld, a 3D cross, is defined in Listing 2, using an XML document conformant with Listing 1.

Listing 2: 3DCross.xml

<?xml version="1.0"?>
<!DOCTYPE blockworld SYSTEM "blockworld.dtd">
<blockworld>
 <head>
  <name>A 3D Cross</name>
  <version release="1" build="0"/>
 </head>
 <world>
  <block x="0" y="1" z="0"
color="red"/>
  <block x="0" y="0" z="0"
color="red"/>
  <block x="0" y="-1" z="0"
color="red"/>
  <block x="1" y="0" z="0"
color="red"/>
  <block x="-1" y="0" z="0"
color="red"/>
  <block x="0" y="0" z="-1"
color="red"/>
  <block x="0" y="0" z="1"
color="red"/>
 </world>
</blockworld>

The result of processing Listing 2 must be the display of the 3D blocks in a screen. For this purpose, use OpenGL, which is the industry library standard for 3D graphics. You will program a Walker that will go through the DOM tree, generating the appropriate OpenGL function calls as it encounters block elements.

Figure 2 shows the final result that you want to achieve (with the exception that in the program the cross is constantly rotating).

Figure 2 BlockWorld C++ Running

The BlockWorldDOMWalker Class

The BlockWorldDOMWalker class is a typical visitor, which goes over a collection of nodes by analyzing them one at the time and then calling itself recursively for each child node.

Listing 3 shows the implementation of the class. Note how a helper class has been defined and is used to read the file from disk into an IXMLDOMNodePtr (in other words, MSXML3 pointer to a DOM Node). A simple inspection reveals that the structure and principles of msxml3 DOM manipulation are the same as those used previously with Xerces, but some names vary. In order to get familiar with the naming conventions, I recommend you read the help file associated with msxml3. (It gets installed under "\Program Files\Microsoft XML Parser SDK\docs\xmlsdk20.chm".)

Listing 3: BlockWorldWalker

include "BlockWorldXMLWalker.h"
/** 
   recursive method used to navigate the tree
  */
void BlockWorldXMLWalker::visit(IXMLDOMNodePtr n)
{
   if(n->nodeType == NODE_ELEMENT)
   {
      if(!strcmp(n->nodeName,"block"))
      {
         // Get the values for each coordinate
         IXMLDOMNodePtr x,y,z,strColor;
         color cubeColor = black;
         n->attributes->get_item(0,&x);
         n->attributes->get_item(1,&y);
         n->attributes->get_item(2,&z);
         n->attributes->get_item(3,&strColor);
         if(!strcmp(strColor->text,"red"))
            cubeColor = red;
         if(!strcmp(strColor->text,"white"))
            cubeColor = white;
         if(!strcmp(strColor->text,"green"))
            cubeColor = green;
         if(!strcmp(strColor->text,"blue"))
            cubeColor = blue;
         if(!strcmp(strColor->text,"purple"))
            cubeColor = purple;
      putCube((int)atoi(x->text), //x,y, and z are bstrs. 
                    // They are converted to ints
               (int)atoi(y->text),
               (int)atoi(z->text),
               cubeColor);
         return; // No interest in looking at the 
             // children of a block (none!)
      }
      else if(!strcmp(n->nodeName,"rotation"))
      {
         // Get the values for each coordinate
         IXMLDOMNodePtr axis,angle;
         n->attributes->get_item(0,&angle);
         n->attributes->get_item(1,&axis);
         if(!strcmp(axis->text,"x"))
           glRotatef((int)atoi(angle->text), 1.0f, 
                0.0f, 0.0f);
         else if(!strcmp(axis->text,"y"))
           glRotatef((int)atoi(angle->text), 
                0.0f, 1.0f, 0.0f);
         else
           glRotatef((int)atoi(angle->text), 
                0.0f, 0.0f, 0.0f);
         // Now traverse the rest of the tree, 
         //looking for more nodes or rotations
         for(int i = 0; i < n->childNodes->length ;i++)
            visit(n->childNodes->item[i]);
         // Now put us back where we started
      if(!strcmp(axis->text,"x"))
            glRotatef(-(int)atoi(angle->text), 
                1.0f, 0.0f, 0.0f);
         else if(!strcmp(axis->text,"y"))
            glRotatef(-(int)atoi(angle->text), 
                0.0f, 1.0f, 0.0f);
         else
            glRotatef(-(int)atoi(angle->text), 
                0.0f, 0.0f, 0.0f);
         return; // Already processed its children!
      }
   }
  // Now traverse the rest of the tree, looking for more nodes or
rotations
    for(int i = 0; i < n->childNodes->length ;i++)
    visit(n->childNodes->item[i]);
}
IXMLDOMNodePtr BlockWorldXMLWalker::Helper::readXMLFile(const char
*name)
{
 try 
 {
  IXMLDOMDocumentPtr docPtr;
  //init
  docPtr.CreateInstance("msxml2.domdocument");
   
  // load a document
  _variant_t varXml(name);
  _variant_t varOut((bool)TRUE);
  varOut = docPtr->load(varXml);
  if ((bool)varOut == FALSE)
   throw(0);
  return docPtr; // remember, a document Node is also a Node 
 } catch(...)
 {
  MessageBox(NULL, "Exception occurred! Malformed or nonexistent
file", "Error", MB_OK);
 }
	return NULL;
}

Even when it is not necessary to know OpenGL to see the XML points of this example, Listing 4 shows the OpenGL code, just in case you are curious about it.

Listing 4: putCube - OpenGL Related Functions

/** 
  put a cube with color col in a particular point of the
world(x,y,z)
  Included here for readability purposes
 */
void putCube(int x,int y,int z,enum color col)
{
 switch(col)
 {
 case black:
  glColor3f(BLACK);
  break;
 case red:
  glColor3f(RED);
  break;
 case blue:
  glColor3f(BLUE);
  break;
 case green:
  glColor3f(GREEN);
  break;
 case purple:
  glColor3f(PURPLE);
  break;
 default:
  glColor3f(WHITE);
  break;
 }
 glTranslatef((float)x*2,(float)y*2,(float)z*2);
 // Draw the sides of the cube
 glBegin(GL_QUAD_STRIP);
 glNormal3d(0.0, 0.0, -1.0); // Normal A
 glVertex3d(1, 1, -1);    // Vertex 1
 glVertex3d(1, -1, -1);   // Vertex 2
 glVertex3d(-1, 1, -1);   // Vertex 3
 glVertex3d(-1, -1, -1);   // Vertex 4
 glNormal3d(-1.0, 0.0, 0.0); // Normal B
 glVertex3d(-1, 1, 1);    // Vertex 5
 glVertex3d(-1, -1, 1);   // Vertex 6
 glNormal3d(0.0, 0.0, 1.0); // Normal C
 glVertex3d(1, 1, 1);    // Vertex 7
 glVertex3d(1, -1, 1);    // Vertex 8
 glNormal3d(1.0, 0.0, 0.0); // Normal D
 glVertex3d(1, 1, -1);    // Vertex 9
 glVertex3d(1, -1, -1);   // Vertex 10
 glEnd();
 // Draw the top and bottom of the cube
 glBegin(GL_QUADS);
 glNormal3d(0.0, 1.0, 0.0);
 glVertex3d(-1, -1, -1);
 glVertex3d(1, -1, -1);
 glVertex3d(1, -1, 1);
 glVertex3d(-1, -1, 1);
 glNormal3d(0.0, 1.0, 0.0);
 glVertex3d(-1, 1, -1);
 glVertex3d(1, 1, -1);
 glVertex3d(1, 1, 1);
 glVertex3d(-1, 1, 1);
 glEnd();
 glTranslatef((float)-x*2,(float)-y*2,(float)-z*2);
}

The Visual Studio DOMWalkerWizard

Now that you have a clear idea of how DOM visitors are implemented with MSXML3, you can factorize the programming portions common to all visitors. Therefore, you can reuse them and concentrate on the DOM visitor logic, instead of writing the same XML-handling code over and over.

The previous Framework, XMLableFR (which is part of the original chapter), was implemented with an open-source Unix system in mind (even though it is runnable and generates correct code for Windows, too). It is based on a free library, it has a command-line interface, it is written in Perl, and it makes no assumptions about your development environment. The next Framework, DOMWalkerWizard, is the other side of the coin: it assumes you are using a commercial product, MSXML3, under Windows, and you are programming using Visual Studio. Both poles are valid, and chances are you have to develop in both of them. I hope you find the broad mix of technologies useful.

What to Factorize?

By inspecting the BlockWorld example, you can see the following common programming elements in all Walkers:

Decide how to traverse the tree (for example, Preorder, Postorder, or Inorder)

  • Decide what types of nodes to take into consideration (for example, only treat elements)

  • Sometimes create a helper class to read the DOM tree from an external source (generally a file)

Our task is to implement this common behavior in the most reusable way, congruent with MSXML and the Visual Studio mechanisms.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020