如何使用 Groovy 构建器 StreamingMarkupBuilder 将 XML 文件转换为 UTF-8

发布于 2024-08-06 16:27:30 字数 683 浏览 3 评论 0原文

尽管问题主题看起来很复杂,但问题很简单。

我使用以下脚本创建一个 XML 文件:

def xmlFile = new File("file-${System.currentTimeMillis()}.xml")
mb = new groovy.xml.StreamingMarkupBuilder()
mb.encoding = "UTF-8"
new FileWriter(xmlFile) << mb.bind {
    mkp.xmlDeclaration()
    out << "\n"
    someMarkup {}
}

然后,当我使用如下代码解析此文件时:

def xml = new XmlSlurper().parse(xmlFile)

我收到以下 MalformedByteSequenceException 异常:

抛出异常:无效的字节 2 3字节UTF-8序列

如果我将文件转换为 UTF-8 格式(例如使用 Notepad++),则一切正常。

那么,如何才能将文件保存为 UTF-8 格式呢?为什么代码 mb.encoding = "UTF-8" 不这样做?

谢谢

Even if the question subject seems complicated, the issue is quite simple.

I create an XML file with the following script:

def xmlFile = new File("file-${System.currentTimeMillis()}.xml")
mb = new groovy.xml.StreamingMarkupBuilder()
mb.encoding = "UTF-8"
new FileWriter(xmlFile) << mb.bind {
    mkp.xmlDeclaration()
    out << "\n"
    someMarkup {}
}

Then when I parse this file using code like:

def xml = new XmlSlurper().parse(xmlFile)

I got the following MalformedByteSequenceException exception:

Exception thrown: Invalid byte 2 of
3-byte UTF-8 sequence

And if I convert the file in UTF-8 format (using Notepad++ for instance) then everything is ok.

So, what can I do to save my file in UTF-8 format? Why the code mb.encoding = "UTF-8" does not do it?

Thx

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以笙箫默 2024-08-13 16:27:30

您需要将输出流编写器包装在 FileOutputStream 上 utf-8 不是默认字符集

new OutputStreamWriter(new FileOutputStream(exportXmlFile),'utf-8') << mb.bind {
    mkp.xmlDeclaration()
    out << "\n"
    someMarkup {}
}

我不确定设置 mb.encoding 的作用,可能只是在 xml 标头中设置字符集

You need to wrap an output stream writer around a FileOutputStream is utf-8 is not the default charset

new OutputStreamWriter(new FileOutputStream(exportXmlFile),'utf-8') << mb.bind {
    mkp.xmlDeclaration()
    out << "\n"
    someMarkup {}
}

I'm not sure what setting mb.encoding does, probably just sets the charset in the xml header

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文