Qt 生成 xml 文件

时间:2022-02-07 11:52:41

代码如下:

	QString filename = QFileDialog::getSaveFileName( this, "Save", "", "*.xml" );

QFile file( filename );
if( !file.open(QIODevice::WriteOnly | QIODevice::Text) )
{
return;
}

QDomDocument document;

QString strHeader( "version=\"1.0\" encoding=\"UTF-8\"" );
document.appendChild( document.createProcessingInstruction("xml", strHeader) );

QDomElement root_elem = document.createElement( "items" );
root_elem.setAttribute( "id", 1 );
document.appendChild( root_elem );

QDomElement item1 = document.createElement( "item" );
item1.setAttribute( "src", "<>" );
item1.setAttribute( "dst", "<>" );
root_elem.appendChild( item1 );

QDomElement item2 = document.createElement( "item" );
item2.setAttribute( "src", "&quot;&apos;&amp;" );
item2.setAttribute( "dst", "\"'&" );
root_elem.appendChild( item2 );

QDomElement item3 = document.createElement( "item" );
item3.setAttribute( "src", tr("测试数据") );
item3.setAttribute( "dst", tr("一二三四") );
root_elem.appendChild( item3 );

QTextStream out( &file );
document.save( out, 4 );
file.close();


生成的 xml 文件为:

Qt 生成 xml 文件

在记事本中查看为:

Qt 生成 xml 文件