PDA

View Full Version : QDomElement::setNodeValue not working!!



arjoshi
2nd May 2011, 16:36
hello:

I have been having problems setting the value of a QDOMElement instance. The following is my code:




int main (int argc, char * argv[])
{
QApplication app(argc,argv);

QDomDocument d("bookml");
QDomElement root = d.createElement("rootelement");
d.appendChild(root);
QDomElement e = d.createElement("BookList");
root.appendChild(e);

QDomElement e0 = d.createElement("BookName");
e.appendChild(e0);
e0.setNodeValue("The Da Vinci Code");
QDomElement e1 = d.createElement("BookPrice");
e1.setNodeValue("45.50");
e.appendChild(e1);


QFile mFile("test.xml");
if ( !mFile.open(QIODevice::WriteOnly ) )
{
std::cout << "Failed creating file" << std::endl;
return -1;
}
QTextStream s(&mFile);
s << d.toString();
mFile.close();
return app.exec();
}


And as output in Internet Explorer I get:




<!DOCTYPE bookml (View Source for full doctype...)>
- <rootelement>
- <BookList>
<BookName />
<BookPrice />
</BookList>
</rootelement>



One can notice that the tags are formed but the values of the BookName and BookPrice which I am supplying using the setNodeValue method are not being seen here.

Any help would be appreciated.

moe
3rd May 2011, 08:55
According to the QDomNode documentation, not all sub classes uses the node value. I belive you have to create a QDomCharacterData or a QDomText node as a child to the QDomElement node, and call setNodeValue(...) on that

alfred.molnar
6th March 2015, 20:42
The following code:
QDomDocument new_doc;
auto RootNode = new_doc.createElement("Root");
QDomText child_node = new_doc.createTextNode("/*this will be ignored*/");
child_node.setNodeValue("value");
new_doc.appendChild(RootNode).appendChild(child_no de);
QString xml_as_string = new_doc.toString();
std::cout<<xml_as_string.toStdString();

Will produce:
<Root>value</Root>

anda_skoa
7th March 2015, 08:38
You can also pass the text to createTextNode() instead of first passing a dummy text and then overwriting it with setNodeValue().

Cheers,
_