1
我想按摩QDomModel示例以从我的DOM文档中删除评论/处理指令,然后在QTreeView中显示内容。我的想法是通过对子元素进行递归函数调用来完成此操作。当我运行下面的代码(实际上并没有调用remove)时,我得到了后面的输出,它正确地遍历所有节点。QDom递归删除评论
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);
}
}
}
输出方式:
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"
不过,当我取消注释removeChild之电话,我得到如下:
Node : "#document" , 9
Node : "xml" , 7
deleting "xml"
显然,当我删除XML节点,该baseGuiConfig节点正在成为节点号码1,然后我正在增加它。我知道我的迭代方式是不正确的,因为我删除了一些,我知道如何用标准迭代器修复这个问题,但我不确定我应该如何用QDom解决这个问题。我是否应该使用removeChild函数的返回值?
这里的,如果需要我的XML文件:
<?xml version="1.0"?>
<baseGuiConfig xsi:noNamespaceSchemaLocation="baseGUIconfig.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<defaults>
<dataDirectory>"C:\"</dataDirectory>
<dataFileExtension>".txt"</dataFileExtension>
<?Just a useless comment?>
</defaults>
</baseGuiConfig>
向后迭代简单优雅,最重要的是解决了问题! – 2014-09-23 16:46:14