使用DOM读取XML文档、使用DOM创建和操作XML文档

使用DOM读取XML文档:

http://www.qter.org/portal.php?mod=view&aid=59

使用DOM创建和操作XML文档:

http://www.qter.org/portal.php?mod=view&aid=60

读取XML:

pro:

QT       += core gui xml

cpp: 

 ConfigWidget* w;

    w = nullptr;

    QDomDocument dom;

    QFile file( "./FlowManagerBase.xml" );

    if( file.open(QIODevice::ReadOnly ) )
    {
        if( dom.setContent( &file ) )
        {
            w = new ConfigWidget( dom );
        }
        else
        {
            QDomDocument domNull;

            w = new ConfigWidget( domNull );
        }

    }

    file.close();

   //读取节点
    QDomElement docElement = dom.documentElement();

    QDomNodeList angleNodeList = docElement.elementsByTagName( TAG_CHANNELS );

    for( int i = 0; i < angleNodeList.size(); i++ )
    {
        QDomNode angleNode = angleNodeList.at( i );

        QDomNodeList channelNameNodeList = angleNode.toElement().elementsByTagName( TAG_CHANNELNAME );

        QString angle = angleNode.toElement().attribute( "Degree" );

        QStringList angleList  = availablePGChannelList;


        for( int j = 0; j < channelNameNodeList.size(); j++ )
        {
            QDomNode channelNode = channelNameNodeList.at( j );

        }

    }

创建XML:

    QDomProcessingInstruction instrution;
    instrution = dom.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"");
    dom.appendChild( instrution );

    QDomNode rootNode = dom.createElement( "Config" );
    dom.appendChild( rootNode );

    QDomNode firstNode = dom.createElement( "Module" );
    firstNode.toElement().setAttribute( "Name", "FlowManager" );
    rootNode.appendChild( firstNode );

    QDomNode thirdNodeDescription = dom.createElement( "Description" );
    QDomText textDescription= dom.createTextNode( "FlowManager is used to ...." );
    thirdNodeDescription.appendChild( textDescription );
    secondNodeDetail.appendChild( thirdNodeDescription );

 将创建的XML写入DOM中

    QFile domFile( "./FlowManagerBase.xml" );

    if ( !domFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
    {
        return;
    }

    QTextStream out( &domFile );

    //将文档保存到文件,4为子元素缩进字符数
    dom.save( out, 4 );

    domFile.close();
创建后得到的文件:
<?xml version='1.0' encoding='UTF-8'?>
<Config>
    <Module Name="FlowManager">
        <Description>FlowManager is used to ....</Description>
    </Module>
</Config>

猜你喜欢

转载自blog.csdn.net/Huahua12342234/article/details/82853640