使用Poco::XML::DOMWriter写入XML时遇变音符号停止问题求助
解决Poco::XML::DOMWriter写入含变音符号XML时停止的问题
我之前也碰到过类似的情况,这个问题几乎可以肯定是编码不匹配导致的。Poco的DOMWriter默认可能采用ASCII编码输出,而ä、ö、ü这类变音符号属于Unicode字符,超出了ASCII的编码范围,写入时就会因为编码错误直接中断,导致文件写到一半就停了。
下面是具体的解决步骤和修改后的代码:
1. 显式设置DOMWriter的输出编码为UTF-8
这是最关键的一步,强制DOMWriter使用UTF-8编码来处理所有字符,这样就能完美支持变音符号这类Unicode字符了。
2. 确保文本节点的字符串是UTF-8编码
如果你的代码里用的是普通的const char*字符串,要确保源代码文件本身是用UTF-8格式保存的;如果是宽字符串,记得先转成UTF-8格式再传入createTextNode。
修改后的完整示例代码
#include <Poco/AutoPtr.h> #include <Poco/DOM/Document.h> #include <Poco/DOM/Element.h> #include <Poco/DOM/Text.h> #include <Poco/DOM/DOMWriter.h> #include <Poco/XML/XMLWriter.h> #include <fstream> using namespace Poco::XML; int main() { AutoPtr<Document> pDoc = new Document; AutoPtr<Element> pRoot = pDoc->createElement("root"); pDoc->appendChild(pRoot); // 包含变音符号的文本节点 AutoPtr<Element> pElement = pDoc->createElement("Element"); // 这里直接用UTF-8编码的字符串,确保源码文件也是UTF-8保存 AutoPtr<Text> pText = pDoc->createTextNode("Example text with umlauts: äöüß"); pElement->appendChild(pText); pRoot->appendChild(pElement); AutoPtr<Element> pElement1 = pDoc->createElement("Element1"); AutoPtr<Text> pText1 = pDoc->createTextNode("Another test: ÄÖÜ"); pElement1->appendChild(pText1); pRoot->appendChild(pElement1); // 关键配置:设置DOMWriter的编码和输出格式 DOMWriter writer; writer.setEncoding("UTF-8"); // 强制使用UTF-8编码 writer.setOptions(XMLWriter::PRETTY_PRINT); // 可选:格式化输出,方便阅读 // 写入XML文件 std::ofstream out("output.xml"); writer.writeNode(out, pDoc); out.close(); return 0; }
额外注意事项
- 编译时如果遇到字符串编码问题,比如GCC编译器,可以添加
-finput-charset=UTF-8参数,确保编译器正确识别源代码中的UTF-8字符串。 - 如果是在Windows系统下,用
std::ofstream的文本模式可能会自动转换换行符,但这不会影响XML的编码内容;如果担心,可以用二进制模式打开文件:std::ofstream out("output.xml", std::ios::binary)。
运行修改后的代码,生成的XML文件开头会自动加上<?xml version="1.0" encoding="UTF-8"?>的声明,里面的变音符号也能完整显示,不会再出现写入中断的情况了。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

