tinyXml输出utf-8文档

TiXmlDocument虽然能读取utf-8的xml文件,但读入后在内存中是以多字节存储。如果新建一个TiXmlDocument,即使定义头为utf-8编码,直接调用SaveFile方法保存的文档仍然是Ansi(windows在CP936下为GBK)。TiXmlDocument不支持直接输出utf-8文档。
网上搜代码遍寻不着,自己摸索出来一个。
这里的编码转换过程是Ansi->Unicode->UTF-8。
Ansi:TiXmlDocument输出到TiXmlPrinter,调用TiXmlPrinter.CStr(),数据类型是char*
Unicode:数据类型WCHAR或CStringW
UTF-8:注意UTF-8的数据类型是char*,或者CStringA
CFile写入文件的方法Write需要两个参数,待写入数据的在内存的起始地址和要写入的字节数
windows平台utf-8文本的前三个字节是EF BB BF,也即BOM(Byte order mark)标记
代码:
XmlEntityTree=new TiXmlDocument;
TiXmlDeclaration *dec=new TiXmlDeclaration("1.0","utf-8","");
XmlEntityTree->LinkEndChild(dec);
TiXmlElement *pRoot=new TiXmlElement("test");
pRoot->SetAttribute("name","名字");
XmlEntityTree->LinkEndChild(pRoot);
TiXmlPrinter printer;
XmlEntityTree->Accept(&printer);

const CStringW UnicodeStr(printer.CStr());
const CStringA UTF8Str=CW2A(UnicodeStr,CP_UTF8);
char UTF8BOM[3]={‘\xEF’,'\xBB’,'\xBF’};

CFile theFile;
theFile.Open(_T("test.xml"),CFile::modeCreate|CFile::modeWrite);
theFile.Write(&UTF8BOM,3);
theFile.Write((LPCSTR)UTF8Str,UTF8Str.GetLength());
theFile.Close();

 

转自:http://blog.sina.com.cn/s/blog_5ebafa150100jo2s.html

posted @ 2019-02-19 17:46  洛洛沙  阅读(847)  评论(0编辑  收藏  举报