我的 xml 例程 :-----
int MainWindow::xmlOpenFile()
{
//set the name of the file
xmlFile.setFileName(xmlFileName);
// open read & write mode
if (!xmlFile.open(QIODevice::ReadWrite|QIODevice::Text))
{
return FAIL_TO_OPEN_FILE;
}
// Assign file to the stream
xmlStream = new QTextStream(&xmlFile);
xmlDomDocument.setContent(&xmlFile);
return SUCCESS_TO_OPEN_FILE;
}
void MainWindow::xmlAddRoot()
{
// Make the root element
xmlRoot = xmlDomDocument.createElement(ROOT_ELEMENT_DETAILS);
// Add it to the document
xmlDomDocument.appendChild(xmlRoot);
}
void MainWindow::xmlCreateNode(QDomElement &NodeElement, QString Name)
{
// Make the node element
NodeElement = xmlDomDocument.createElement(Name);
}
void MainWindow::xmlAddTextNode(QDomElement &NodeElement, QString textContent)
{
QDomText textNode;
textNode = xmlDomDocument.createTextNode(textContent);
NodeElement.appendChild(textNode);
}
void MainWindow::xmlAppendNode(QDomElement &xmlParent, QDomElement &xmlChild)
{
xmlParent.appendChild(xmlChild);
}
empty
这是我在XML 文件中输入文本的程序, MyXML.xml
:----
xmlFileName = "D:/Temp/MyXML.xml";
xmlOpenFile();
xmlAddRoot();
xmlCreateNode(xmlTempNode, "hello");
xmlAddTextNode(xmlTempNode, "hi" );
xmlAppendNode(xmlRoot,xmlTempNode);
xmlCreateNode(xmlTempNode, "hello 0");
xmlAddTextNode(xmlTempNode, "hi 0" );
xmlAppendNode(xmlRoot,xmlTempNode);
xmlCreateNode(xmlTempNode, "hello -1");
xmlCreateNode(xmlTempNodeChild, "hello -1 - 1");
xmlAddTextNode(xmlTempNodeChild, "hi -1 - 1" );
xmlAppendNode(xmlTempNode,xmlTempNodeChild);
xmlCreateNode(xmlTempNodeChild, "hello -1 - 2");
xmlAddTextNode(xmlTempNodeChild, "hi -1 - 2" );
xmlAppendNode(xmlTempNode,xmlTempNodeChild);
xmlAppendNode(xmlRoot,xmlTempNode);
xmlCreateNode(xmlTempNode, "hello -2");
xmlAddTextNode(xmlTempNode, "hi -2" );
xmlAppendNode(xmlRoot,xmlTempNode);
// Here i am replacingthe node, hello -1
QDomNode temp_1 = xmlRoot.firstChild().nextSibling().nextSibling();
QDomNode temp = temp_1;
QDomElement element = temp.toElement();
QDomNode n = element.firstChild();
QDomText t = n.toText();
t.setData("Here is the new text");
//Replace node "hello -1"
xmlRoot.replaceChild(temp,temp_1);
xmlCloseFile();
在上面的代码中,我创建了 4 个节点to root
测试用例,然后我修改了第三个孩子xmlRoot.firstChild().nextSibling().nextSibling();
,但更改没有反映在最终的 xml 文件中
它创建了以下 xml 文件:----
<Test Cases>
<hello>hi</hello>
<hello 0>hi 0</hello 0>
<hello -1>
<hello -1 - 1>hi -1 - 1</hello -1 - 1>
<hello -1 - 2>hi -1 - 2</hello -1 - 2>
</hello -1>
<hello -2>hi -2</hello -2>
</Test Cases>
但我想用以下内容替换"hello -1"
节点:---
<hello -1>
<hello -1 - 1>Here is the new text</hello -1 - 1>
<hello -1 - 2>hi -1 - 2</hello -1 - 2>
</hello -1>
为什么替换孩子不起作用?