我使用libxml和c ++创建了一个xml文件。我现在想做的是从.txt中读取内容,并将此文本放在某些特定标签之间。
我尝试了以下代码,只是从文件中读取并在标签之间写入它:
char * s ;
double d;
fichier>>i>>s>>d;
// fichier.close();
cout << s << endl ;
xmlNewChild(root_node, NULL, BAD_CAST "metadata",
BAD_CAST s );
运行此代码时,出现以下错误:
output error : string is not in UTF-8
因此,我猜想输入和输出之间存在格式不兼容的问题。你能帮我吗?我不知道该如何解决。
最佳答案
您需要使用编码模块中定义的功能之一将输入字符串转换为UTF-8输入。 (或者使用其他喜欢icu的编码库),您可以在http://www.xmlsoft.org/html/libxml-encoding.html处找到有关编码模块的详细信息
我的猜测是,您想保留字节,以便所需的内容是这样的(非常未经测试,并且完全来自文档。)
//Get the encoding
xmlCharEncodingHandlerPtr encoder = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_ASCII);
// Each ascii byte should take up at most 2 utf-8 bytes IIRC so allocate enough space.
char* buffer_utf8 = new char[length_of_s*2];
//Do the encoding
int consumed = length_of_s;
int encoded_length=length_of_s*2;
int len = (*encoder.input)(buffer_utf8, &encoded,s,&consumed);
if( len<0 ) { .. error .. }
buffer_utf8[len]=0; // I'm not sure if this is automatically appended or not.
//Now you can use buffer_utf8 rather than s.
如果您的输入使用libxml支持的不同编码,则只需将
XML_CHAR_ENCODING_ASCII
更改为正确的常数即可,尽管您可能还需要更改buffer_utf8
中分配的字节数。关于c++ - 使用libxml和c++创建xml时关于UTF_8格式的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15779063/