phpwap

C++博客 联系 聚合 管理
  0 Posts :: 4 Stories :: 0 Comments :: 0 Trackbacks

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)标记

代码:

01 XmlEntityTree=new TiXmlDocument;
02 TiXmlDeclaration *dec=new TiXmlDeclaration("1.0","utf-8","");
03 XmlEntityTree->LinkEndChild(dec);
04 TiXmlElement *pRoot=new TiXmlElement("test");
05 pRoot->SetAttribute("name","名字");
06 XmlEntityTree->LinkEndChild(pRoot);
07 TiXmlPrinter printer;
08 XmlEntityTree->Accept(&printer);
09  
10 const CStringW UnicodeStr(printer.CStr());
11 const CStringA UTF8Str=CW2A(UnicodeStr,CP_UTF8);
12 char UTF8BOM[3]={'\xEF','\xBB','\xBF'};
13  
14 CFile theFile;
15 theFile.Open(_T("test.xml"),CFile::modeCreate|CFile::modeWrite);
16 theFile.Write(&UTF8BOM,3);
17 theFile.Write((LPCSTR)UTF8Str,UTF8Str.GetLength());
18 theFile.Close();
posted on 2010-10-20 17:58 涣熊 阅读(123) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理