XML lo puoi rappresentare come un albero n-ario.
Mi sono ricordato di aver scritto una funzione per la stampa di un file XML.
Sibling sono i nodi fratelli e child i figli
codice:
string XMLNode::printXML ( const XMLNode * curEl, unsigned int tab ) const
{
string loc_print = "";
string p_tab = "";
if ( curEl ) {
TYPE type = curEl->type () ;
switch ( type ) {
case ELEMENT : {
XMLElement * el = ( XMLElement *) curEl;
string tagName = curEl->value ();
loc_print += p_tab + "<" + tagName ;
for ( XMLAttribute * att = el->getAttributes() ; att; att = att->next ) {
string name = att->name ();
string value = att->value ();
if ( value != "" )
loc_print += " " + name + "=\"" + value + "\"";
}
if ( curEl->hasChilds() ) {
loc_print += ">\n";
if ( tab )
loc_print += printXML ( curEl->fChild, tab + 1 );
else
loc_print += printXML ( curEl->fChild, tab );
// chiude il tag
if ( tagName != "" ) {
loc_print += p_tab + "</" + tagName + ">\n";
}
}
else {
if ( tagName == "br" || tagName == "img" || tagName == "link" )
loc_print += " />\n";
else
loc_print += "></" + tagName + ">\n";
}
}
break;
case TEXT :
loc_print = p_tab + curEl->value () + "\n";
break;
case DOCUMENT :
if ( curEl->hasChilds() )
loc_print += printXML ( curEl->fChild, tab );
break;
case COMMENT :
loc_print = p_tab + "<-- " + curEl->value () + "-->\n";
break;
case UNKNOWN :
break;
case DECLARATION :
break;
case DOCTYPE :
loc_print = "<!DOCTYPE " + curEl->value () + ">\n";
break;
case SCRIPT :
loc_print = p_tab + "<? " + curEl->value () + "?>\n";
break;
default :
break;
}
if ( curEl->fSibling )
loc_print += printXML ( curEl->fSibling, tab );
}
return loc_print;
}
tab può essere utile per conoscere la profondità.
type è il tipo di nodo e value il suo valore (che tipende dal suo tipo).
Te la passo in modo che dai una occhiata alla sua logica.
ciao
sergio