Parsing XML
by David Cox

Example 1:
(a)
<Address><Name>David</Name><Street>1 Main St</Street>
<City>Anywhere</City><State>NY</State><Zip>90210</Zip></Address>


(b)
<Address>
    <Name>
        David
    </Name>
    <Street>
        Main Street
    </Street>
    <City>
        Anywhere
    </City>
    <State>
        NY
    </State>
    <Zip>
        90210
    </Zip>
</Address>


Listing One
void Parser::StartTag(Tag * t)
{
    std::string buffer;
    Match(m_leftStartAngle);    // match "<"
    TagName(buffer);            // match tag name
    if (t) t->Name(buffer);     // save tag name
    if (m_lookahead != m_rightStartAngle)
    {
        AttributeList(t);       // match attributes
    }
    Match(m_rightStartAngle);   // match ">"
}
EndTag( ) is even simpler:
void Parser::EndTag()
{
    std::string tagName;
    Match(m_leftEndAngle);      // match "</"
    TagName(tagName);           // match tag name
    Match(m_rightEndAngle);     // match ">"
}

Listing Two
#include <parser.h>
#include <tagiterator.h>
#include <iostream>

void main(int argc, char *argv[]) {
    Parser p;
    ifstream xmlFile(argv[1]);
    p.Translate(xmlFile);
    Tag * root = p.GetRoot();
    TagIterator ti(root);
    Tag * next = ti.Begin();  // get the root of the tree
    while (next)
    {
        next->Visit(ti.Level());  // Visit prints the tag
        next = ti.Next();         // get the next tag in the tree
    }
    exit(0);
}



2

