2013-05-03 22 views

回答

2

沒有API將XML片段作爲文本「注入」到QDomDocument(或QXmlStreamWriter)中。必須使用API​​並以編程方式創建節點。

+0

這就是說,他們在Qt DOM中不提供這樣的功能令人傷心。畢竟,你經常最終必須這樣做,並且他們已經編寫了「完美」解析器,並且可以從內部訪問...... – 2013-11-21 01:06:34

1

假設你有一個字符串開始,我目前的解決辦法是從其生成一個DOM樹,進口該樹的片段,然後複製那些在正確的地方(你必須有一個進口這就是爲什麼你需要中間片段。如果你問我挺可惜。)

// assuming that 'n' is the node you are replacing or at least inserting after 
// 'parent' is the parent of 'n' 
// 'result' is the string to replace 'n' or insert after 'n' 
QDomDocument doc_text("snap"); 
doc_text.setContent("<text>" + result + "</text>", true, NULL, NULL, NULL); 
QDomDocumentFragment frag(xml.createDocumentFragment()); 
frag.appendChild(xml.importNode(doc_text.documentElement(), true)); 
QDomNodeList children(frag.firstChild().childNodes()); 
const int max(children.size()); 
QDomNode previous(n); 
for(int i(0); i < max; ++i) 
{ 
    QDomNode l(children.at(0)); 
    parent.insertAfter(children.at(0), previous); 
    previous = l; 
} 
// if you are replacing, then delete node n as well 
parent.removeChild(n); 

注意,<文本>標籤被用來使這樣的結果並不需要是一個標籤,它可能只是文本,它仍然可以工作。

顯然,如果您從其他文檔開始的片段或XML,請忽略在doc_text對象中創建該代碼的代碼。