2011-04-20 42 views
0

我在Mac OS X上使用Qt 4.7,並且我有一個QString包含一個XML文件的路徑。我想將該文件導入到DOM樹中,並將數據作爲成員變量存儲到類中。做這個的最好方式是什麼?導入XML到Qt中的DOM樹

我一直在尋找QtXml文檔,但我找不到一個明確的方法將QXml*類轉換爲QDom*類。

回答

2

我不認爲你需要打擾QXml *類來遍歷DOM。

QDomDocument類有一個setContent()方法,它可以打開QFile。

There's a code sample在QDomDocument文檔的「詳細信息」部分。

QDomDocument doc("mydocument"); 
QFile file("mydocument.xml"); 
if (!file.open(QIODevice::ReadOnly)) 
    return; 
if (!doc.setContent(&file)) { 
    file.close(); 
    return; 
} 
file.close(); 

// print out the element names of all elements that are direct children 
// of the outermost element. 
QDomElement docElem = doc.documentElement(); 

QDomNode n = docElem.firstChild(); 
while(!n.isNull()) { 
    QDomElement e = n.toElement(); // try to convert the node to an element. 
    if(!e.isNull()) { 
     cout << qPrintable(e.tagName()) << endl; // the node really is an element. 
    } 
    n = n.nextSibling(); 
}