Edit Value of a QDomElement?

折月煮酒 提交于 2019-11-27 02:43:12

问题


I need to edit the text of a QDomElement - Eg

I have an XML file with its content as -

<root>    
    <firstchild>Edit text here</firstchild>
</root>

How do I edit the text of the child element <firstchild>?

I don't see any functions in the QDomElement of QDomDocument classes descriptions provided in Qt 4.7

Edit1 - I am adding more details.

I need to read, modify and save an xml file. To format of the file is as below -

<root>    
    <firstchild>Edit text here</firstchild>
</root>

The value of element needs to be edited.I code to read the xml file is -

QFile xmlFile(".\\iWantToEdit.xml");
xmlFile.open(QIODevice::ReadWrite);

QByteArray xmlData(xmlFile.readAll());

QDomDocument doc;
doc.setContent(xmlData);

// Read necessary values

// write back modified values?

Note: I have tried to cast a QDomElement to QDomNode and use the function setNodeValue(). It however is not applicable to QDomElement.

Any suggestions, code samples, links would we greatly welcome.


回答1:


This will do what you want (the code you posted will stay as is):

// Get element in question
QDomElement root = doc.documentElement();
QDomElement nodeTag = root.firstChildElement("firstchild");

// create a new node with a QDomText child
QDomElement newNodeTag = doc.createElement(QString("firstchild")); 
QDomText newNodeText = doc.createTextNode(QString("New Text"));
newNodeTag.appendChild(newNodeText);

// replace existing node with new node
root.replaceChild(newNodeTag, nodeTag);

// Write changes to same file
xmlFile.resize(0);
QTextStream stream;
stream.setDevice(&xmlFile);
doc.save(stream, 4);

xmlFile.close();

... and you are all set. You could of course write to a different file as well. In this example I just truncated the existing file and overwrote it.




回答2:


Just to update this with better and simpler solution (similar like Lol4t0 wrote) when you want to change the text inside the node. The text inside the 'firstchild' node actually becomes a text node, so what you want to do is:

...
QDomDocument doc;
doc.setContent(xmlData);
doc.firstChildElement("firstchild").firstChild().setNodeValue(‌​"new text");

notice the extra firstChild() call which will actually access the text node and enable you to change the value. This is much simpler and surely faster and less invasive than creating new node and replacing the whole node.




回答3:


what is the problem. What sort of values do you want to write? For example, the fallowing code converts this xml

<?xml version="1.0" encoding="UTF-8"?>
<document>
    <node attribute="value">
        <inner_node inner="true"/>
        text
    </node>
</document>

to

<?xml version='1.0' encoding='UTF-8'?>
<document>
    <new_amazing_tag_name attribute="foo">
        <bar inner="true"/>new amazing text</new_amazing_tag_name>
</document>

Code:

QFile file (":/xml/document");
file.open(QIODevice::ReadOnly);
QDomDocument document;
document.setContent(&file);
QDomElement documentTag = document.documentElement();
qDebug()<<documentTag.tagName();

QDomElement nodeTag = documentTag.firstChildElement();
qDebug()<<nodeTag.tagName();
nodeTag.setTagName("new_amazing_tag_name");
nodeTag.setAttribute("attribute","foo");
nodeTag.childNodes().at(1).setNodeValue("new amazing text");

QDomElement innerNode = nodeTag.firstChildElement();
innerNode.setTagName("bar");
file.close();

QFile outFile("xmlout.xml");
outFile.open(QIODevice::WriteOnly);
QTextStream stream;
stream.setDevice(&outFile);
stream.setCodec("UTF-8");
document.save(stream,4);
outFile.close();



回答4:


Here is a version of your code that does what you need. Note as spraff said, the key is finding the child of the "firstchild" node of type text - that's where the text lives in the DOM.

   QFile xmlFile(".\\iWantToEdit.xml");
    xmlFile.open(QIODevice::ReadWrite);

    QByteArray xmlData(xmlFile.readAll());

    QDomDocument doc;
    doc.setContent(xmlData);

    // Get the "Root" element
     QDomElement docElem = doc.documentElement();

    // Find elements with tag name "firstchild"
    QDomNodeList nodes = docElem.elementsByTagName("firstchild"); 

    // Iterate through all we found
    for(int i=0; i<nodes.count(); i++)
    {
        QDomNode node = nodes.item(i);

        // Check the node is a DOM element
        if(node.nodeType() == QDomNode::ElementNode)
        {
            // Access the DOM element
            QDomElement element = node.toElement(); 

            // Iterate through it's children
            for(QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
            {
                // Find the child that is of DOM type text
                 QDomText t = n.toText();
                 if (!t.isNull())
                 {
                    // Print out the original text
                    qDebug() << "Old text was " << t.data();
                    // Set the new text
                    t.setData("Here is the new text");
                 }
            }
        }
    }

    // Save the modified data
    QFile newFile("iEditedIt.xml");
    newFile.open(QIODevice::WriteOnly);
    newFile.write(doc.toByteArray());
    newFile.close();



回答5:


Go up an abstraction level to QDomNode. firstchild is a QDomText element so you can get value() and setValue(x) to work with the text itself.



来源:https://stackoverflow.com/questions/6753782/edit-value-of-a-qdomelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!