Tree evaluation

Top  Previous  Next

Examples > XML > Tree evaluation

 

To transform the structure of a document into a tree at first, instead of transforming it directly into the desired form, has the advantage that an access on the data is possible now in arbitrary order and repeatedly. The output of the data can be organized now very systematically and to write the same data in different formats, e.g. Html and Rtf, can be done by similar procedures.

 

In this exercise example the XML document shall simply be issued in the form of simple text.

 

The procedures for the output of the tree data are assembled into a common container.

 

mstrfun                m_PrintText;

 

The mstrfun is a function table: mstrfun contains member functions, which will be applied on nodes, the label which of is the key of the function in the table.

 

The table is initialized as follows:

 

{{

m_PrintText.add("", DontPrint);

m_PrintText.add("document", DocText);

m_PrintText.add("element", ElementText);

m_PrintText.add("content", ContentText);

m_PrintText.add("Attributes", AttributesText);

}}

 

That means, for a node with the label "document" the function with the name "DocText" shall be executed; for a node with the label "element" the function with the name "ElementText" shall be executed ... In the first instruction a default function is added to the table, which shall be executed for all nodes with a label not contained as key in the table.

 

The functions DocText, ElementText, CharDataText and DontPrint all are defined on the  pagefor class elements. The function DocText has to be called for the root of the tree:

 

{{

node pos = xNode.firstChild();

while(pos != node::npos)

{

m_PrintText.visit(pos);

pos = pos.nextSibling();

}

}}

 

Here for all child nodes of the root m_PrintText.visit(xState, pos) is called.

The visit method of a function table is the cardinal point of the whole tree evaluation. This method redirects the node argument pos to the function, which matches the label of the node. You can read the visit-function in this example as an abbreviation of:

 

if(xNode.label() == "document")

{

DocText(xNode);

}

else

if(xNode.label() == "element")

{

ElementText(xNode);

}

else

if(xNode.label() == "CharData")

{

CharDataText(xNode);

}

else

{

DontPrint(xNode);

}

 

The function ElementText is constructed as DocText, with the difference, that the value of the node is issued:

 

out << indent << xNode.value() << endl;

 

before the sub nodes are visited. So, beginning at the root node all nodes are passed systematically up to the leaf nodes. There the function CharDataText outputs its value.

 

 



This page belongs to the TextTransformer Documentation

Home  Content  German