Modify an XML file QXMLStreamReader/Writer

后端 未结 1 1826
醉酒成梦
醉酒成梦 2021-01-15 04:04

I am working on something where I am using QXMLStreamReader and QXMLStreamWriter, to read and write to a file.

But am not able to find a wa

1条回答
  •  野的像风
    2021-01-15 04:33

    You can use QDomDocument to store content from XML. You can create new child, tag, attribute.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        QFile file("test.xml");
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qDebug() << "Failed to open file";
            return 0;
        }
        QDomDocument document;
        if (!document.setContent(&file))
        {
            qDebug() << "failed to parse file";
            file.close();
            return 0;
        }
    
        file.close();
    
        QDomElement docEle = document.documentElement();
        QDomNodeList elements = docEle.elementsByTagName("LAMPS");
    
        QDomElement light1 = document.createElement( "LIGHT1" );
        QDomElement state = document.createElement("State");
        QDomText nextNode = document.createTextNode("State");
        state.appendChild(nextNode);
        light1.appendChild(state);
        docEle.appendChild( light1 );
    
        QFile outFile( "test-result.xml" );
        if( !outFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
        {
            qDebug( "Failed to open file for writing." );
            return 0;
        }
    
        QTextStream stream( &outFile );
        stream << document.toString();
    
        outFile.close();
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题