Re: [xml] traverse a tree



It seems to work, but I don't know if there is a more efficient or/and a simpler way in achieving this. 
Can somebody tell me if there are mistakes I made?
Hi

adding some typechecking on your nodes will make your tree parsing (more) correct. 

more precisely add the test cur->type==XML_ELEMENT_NODE before calling recursivily the function and before 
testing (cur->name) else your parsing will indifferently jump into potentially included embedded dtd, 
comments, attributes, and text nodes and continue parsing there... as you can see with following "dump" 
function (equivalent to yours)

void rec(xmlNodePtr d) {
  xmlNodePtr cur=d->children;
  while(cur) {
    printf("cur->type=%d    cur->name=%s\n",cur->type,cur->name);
    rec(cur);
    cur=cur->next;
  }
}

Concerning efficiency/simplification - it depends on what you want to do - here you will not keep much 
information from xml structure - 
but no there is no simpler way to explore a tree

Jean S.


Matthias Pieroth writes:
Hi list,

I want to parse a tree and read out the attribues and values. I wrote two functions to do so:

void CXMLTreeWalk::getPropsFromChildren(xmlDocPtr doc, xmlNodePtr cur){

xmlChar* szText;

static int iYPos;

int iXPos, iLength;

cur = cur->xmlChildrenNode;

while (cur != NULL) {

if ((!xmlStrcmp(cur->name, (const xmlChar *) RECORDNODE))) {

iYPos = getIntProp(cur,"YPos");

printf("YPOS %d\n", iYPos);

}

if ((!xmlStrcmp(cur->name, (const xmlChar *) TEXTNODE))) {

iXPos = getIntProp(cur,"XPos");

printf(" XPOS %d\n", iXPos);

iLength = getIntProp(cur,"Length");

szText = xmlNodeListGetString(doc,cur->xmlChildrenNode, 1);

xmlFree(szText);

}

getPropsFromChildren(doc,cur);

cur = cur->next;

}

return;

}

void CXMLTreeWalk::traverseTree()

{

while(m_cur != NULL) {

if((!xmlStrcmp(m_cur->name, (const xmlChar *) ROOTNODE)))

{

getPropsFromChildren(m_doc, m_cur);

}

m_cur=m_cur->next;

}

}

It seems to work, but I don't know if there is a more efficient or/and a simpler way in achieving this. 
Can somebody tell me if there are mistakes I made?

Matthias




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]