libXML2无法正确读取自己的XML UTF-8格式
我想用libXML2解析UTF8格式的XML。 我的代码是用C编写的,我使用libXML2的v2.9.3 我的代码如下:libXML2无法正确读取自己的XML UTF-8格式,utf-8,libxml2,Utf 8,Libxml2,我想用libXML2解析UTF8格式的XML。 我的代码是用C编写的,我使用libXML2的v2.9.3 我的代码如下: xmlTextReaderPtr reader; xmlTextWriterPtr writer; writer = xmlNewTextWriterFilename("test.xml", 0); xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL); xmlTextWrite
xmlTextReaderPtr reader;
xmlTextWriterPtr writer;
writer = xmlNewTextWriterFilename("test.xml", 0);
xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL);
xmlTextWriterStartElement(writer, BAD_CAST "node_with_é_character");
xmlTextWriterEndElement(writer);
xmlTextWriterEndDocument(writer);
xmlFreeTextWriter(writer);
reader = xmlReaderForFile("test.xml", "UTF-8", XML_PARSE_RECOVER);
int ret = 1;
while (ret == 1) {
const xmlChar *nameT = xmlTextReaderConstName(reader);
printf("\n ---> %s\n",nameT);
ret = xmlTextReaderRead(reader);
}
输出为:
---> (null)
---> node_with_é_character
问题是带有字符跟踪的节点,而不是带有字符跟踪的节点
我的命令提示符是chcp 1252 set
我不明白为什么liXML2不能存储/读取字符。正如您在Windows下的注释中所指出的,所以我猜您的源代码可能不是UTF-8编码的,所以带有字符的C字符串节点不是UTF-8编码的 我不知道libxml2接口,但代码示例非常清楚,它需要UTF-8中的输入参数。看
将源文件另存为UTF-8将帮助您解决问题。您在Windows上,不是吗?是的,我在Windows上使用mingw。字符é用两个字节C3和A9保存。如果这两个字节被解释为用拉丁语-1或类似的Windows代码页解码,则会得到é代替。因此,我认为您的代码是正确的,但是您的终端/命令行工具接收程序的输出并显示它,但它出错了。您应该将命令行界面的编码设置为UTF-8。您说得对。将命令提示符设置为chcp 65001并将源文件转换为UTF-8已解决问题。谢谢
/* Write a comment as child of EXAMPLE.
* Please observe, that the input to the xmlTextWriter functions
* HAS to be in UTF-8, even if the output XML is encoded
* in iso-8859-1 */
tmp = ConvertInput("This is a comment with special chars: <\xE4\xF6\xFC>",
MY_ENCODING);