Example Shopping List

This section discusses the usage of various methods by applying several code snippets to a sample document object.

    <PRICE unit="1 lb">.98</PRICE>
    <PRICE unit="3 lb bag">1.10</PRICE>

The document above could be created using the following code:

CMarkup doc;
doc.AddElem( "ORDER" );
doc.AddChildElem( "ITEM" );
doc.AddChildElem( "NAME", "carrots" );
doc.AddChildElem( "QTY", "1" );
doc.AddChildElem( "PRICE", ".98" );
doc.SetChildAttrib( "unit", "1 lb" );
doc.AddElem( "ITEM" );
doc.AddChildElem( "NAME", "onions" );
doc.AddChildElem( "QTY", "1" );
doc.AddChildElem( "PRICE", "1.10" );
doc.SetChildAttrib( "unit", "3 lb bag" );
doc.AddChildElem( "SUPPLIER", "Hanover" );

You can navigate to the PRICE child element in the first ITEM element as follows:


Now that the child position is the PRICE element, doc.GetChildTagName() returns PRICE, doc.GetChildData() returns .98, and doc.GetChildAttrib("unit") returns 1 lb.

<PRICE unit="1 lb">.98</PRICE>

When the main position is the ITEM and the child position is the PRICE element, getting to the next ITEM can be done by calling doc.FindElem() or doc.FindElem("ITEM"). This invalidates the child position, preparing it for a FindChildElem within the newly current ITEM element.

You can also call doc.OutOfElem() (the opposite of doc.IntoElem()) to retreat one level up, making the ORDER the main position and the ITEM the child position. Then call doc.FindChildElem("ITEM") to set the child position to the next item.

To calculate the total bill, loop through all items and total the products of quantity * price.

double dTotal = 0;
while ( doc.FindChildElem("ITEM") )

    int nQty = 0;
    if ( doc.FindChildElem("QTY") )
        nQty = atoi(doc.GetChildData());
    if ( doc.FindChildElem("PRICE") )
        dTotal += (double)nQty * atof(doc.GetChildData());