Example Shopping List

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

<ORDER>
  <ITEM>
    <NAME>carrots</NAME>
    <QTY>1</QTY>
    <PRICE unit="1 lb">.98</PRICE>
  </ITEM>
  <ITEM>
    <NAME>onions</NAME>
    <QTY>1</QTY>
    <PRICE unit="3 lb bag">1.10</PRICE>
    <SUPPLIER>Hanover</SUPPLIER>
  </ITEM>
</ORDER>

The document above could be created using the following code:

CMarkup doc;
doc.AddElem( "ORDER" );
doc.AddChildElem( "ITEM" );
doc.IntoElem();
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:

doc.FindChildElem("ITEM");
doc.IntoElem();
doc.FindChildElem("PRICE");

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;
doc.ResetPos();
while ( doc.FindChildElem("ITEM") )
{
    doc.IntoElem();

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

    doc.OutOfElem();
}