I'm trying to massage the QDomModel example to remove comments/processing instructions from my DOM document prior to displaying the contents in a QTreeView. My thought was to do this with a recursive function call on the child elements. When I run the code below (which doesn't actually call remove), I get the output that follows, which iterated over all the nodes correctly.
void QDomModel::removeComments(QDomNode &node)
{
QString name = node.nodeName();
int i = node.nodeType();
qDebug() << "Node : " << name << ", " << i;
if (node.hasChildNodes())
{
// call remove comments recursively on all the child nodes
for (int i=0; i<node.childNodes().count(); i++)
{
QDomNode child = node.childNodes().at(i);
// Uh-oh, recursion!!
removeComments(child);
}
}
else
{
// if the node has no children, check if it's a comment
if (node.nodeType() == QDomNode::ProcessingInstructionNode ||
node.nodeType() == QDomNode::CommentNode)
{
qDebug() << "deleting " << name;
// if so, get rid of it.
//node.parentNode().removeChild(node);
}
}
}
Output:
Node : "#document" , 9
Node : "xml" , 7
deleting "xml"
Node : "baseGuiConfig" , 1
Node : "defaults" , 1
Node : "dataDirectory" , 1
Node : "#text" , 3
Node : "dataFileExtension" , 1
Node : "#text" , 3
Node : "Just" , 7
deleting "Just"
However, when I un-comment the removeChild call, I get the following:
Node : "#document" , 9
Node : "xml" , 7
deleting "xml"
Clearly, when I remove the xml node, the baseGuiConfig node is becoming node number 1 and then I'm incrementing over it. I know that my way of iterating through the children is not correct given I'm deleting some, and I'd know how to fix this with standard iterators, but I'm not sure how I'm supposed to get around this with QDom. I Am I supposed to use the return value of the removeChild function somehow?
Here's my XML file if needed:
<?xml version="1.0"?>
<baseGuiConfig xsi:noNamespaceSchemaLocation="baseGUIconfig.xsd" xmlns:xsi="http://ift.tt/ra1lAU">
<defaults>
<dataDirectory>"C:\"</dataDirectory>
<dataFileExtension>".txt"</dataFileExtension>
<?Just a useless comment?>
</defaults>
</baseGuiConfig>
No comments:
Post a Comment