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