c++ - 使用 libxml 和 c++ 创建我的 xml 时有关 UTF_8 格式的错误

标签 c++ xml dom libxml2

我使用 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/

相关文章:

c++ - 用数据点填充矩阵

c# - TextBox 中不显示换行符

xml - 关于为 XML 配置文件创建 GUI 的建议

Java jsoup 选择内容

java - JSoup:如何选择包含多个表的页面中的第一个表

c++ - 即使有时间延迟,cout 也不打印

c++ [] with vector< vector<int>>

c++ - 在 CEF 客户端中拖动时的图像预览

java - 如何将 jaxp 3 与 jdk 1.6 一起使用?

java - 从 DOM 中删除节点