在QT里,正常xml读写方式有QtDom,QtSreamerReader方式。这里主要使用dom方式。此种方式可以直接将xml文件读入内存中形成Dom树,然后解析xml。具体的解析方式,这里不在赘述。网络上很多将Dom树写入xml的过程详解。这里也不在讨论范围之内。这里研究的是,在内存里的Dom树xml直接通过内存流的方式保存并通过socket发出。QDomDocument类提供了toString方法,旨在将Dom树转换为QString方式。但是值得注意的是,转换为的QString并不能直接传输给socket。如果此时将Qstring的constData取出,并保存到QChar类型的数组里,你会发现QChar数组里保存的内容编码为双字节编码。即一个‘代码如下: QMessageBox *pMessageBox = new QMessageBox; if(pMessageBox == NULL) {     return -1; } if(xmlPath.size() == 0) {     pMessageBox->information(this,tr("Error!"),tr("xml is not valid!"));     delete pMessageBox; r    eturn -1; } QFile file(xmlPath); //注册xml文件到文件内 if(!file.open(QFile::ReadOnly)) //打开文件 {     pMessageBox->information(this,tr("Error!"),tr("xml can not open!"));     delete pMessageBox;     return -1; } QDomDocument doc; if(!doc.setContent(&file)) //转换为QDomDocument {     pMessageBox->information(this,tr("Error!"),tr("xml doc create failed!"));     delete pMessageBox;     return -1; } SendBuf.clear(); //QString 类的sendbuf SendBuf = doc.toString(-1); //去掉空格方式转换 file.close(); *iSendLen = ba.size(); delete pMessageBox; 此时,内存里的数据保存图为:    可见,一个为了解决上述问题,在toString后,加入以下代码:QByteArray ba = pSendBuf.toLatin1(); *outBuf = (char *)malloc(pSendBuf.size()); memset(*outBuf,0,pSendBuf.size()); strcpy(*outBuf,ba.constData());可以使得内存编码正确。究其原因是,QChar方式以双字节编码。char以单字节编码。
09-22 06:56