【问题标题】:How to convert XML file in UTF-8 using Groovy builder StreamingMarkupBuilder如何使用 Groovy 构建器 StreamingMarkupBuilder 将 XML 文件转换为 UTF-8
【发布时间】:2010-12-04 10:57:53
【问题描述】:

即使题目看起来很复杂,其实问题也很简单。

我使用以下脚本创建了一个 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" 不做呢?

谢谢

【问题讨论】:

标签: xml grails utf-8 groovy markupbuilder


【解决方案1】:

您需要在 FileOutputStream 周围包裹一个输出流编写器是 utf-8 不是默认字符集

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

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

【讨论】:

    猜你喜欢
    • 2011-09-14
    • 2013-10-10
    • 2015-09-19
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多