登录
首页 >  Golang >  Go问答

解析XML文件时如何使用MACROMAN编码

来源:stackoverflow

时间:2024-03-27 09:42:32 102浏览 收藏

在解析XML文件时,若遇到“不支持的字符集:MACROMAN”错误,可以通过使用特定编码器解决。由于MACROMAN不在Go语言默认支持的Macintosh编码别名列表中,需要自定义别名列表,并将charsetreader函数字段设置为自定义别名列表。该函数将检测MACROMAN编码并使用Macintosh编码器对输入数据进行转换。通过设置charsetreader函数,可以解析具有MACROMAN编码的XML文件。

问题内容

我正在尝试解析给定的 pom 内容,但出现错误:xml:打开字符集“macroman”:不支持的字符集:“macroman”。 我尝试通过设置 detector.strict = false 来禁用严格编码 但这也不起作用。

这是 go 演示链接,我正在其中解析这个特定的 pom。任何帮助/参考将不胜感激。



 
   org.eclipse.vorto
   org.eclipse.vorto.parent
   0.10.0.M1
 
 4.0.0
 generators
 
 Eclipse Vorto Code Generators
 pom
 
        org.eclipse.vorto.codegen.thingworx
        org.eclipse.vorto.codegen.javabean
        org.eclipse.vorto.codegen.mqtt
        org.eclipse.vorto.codegen.webui
        org.eclipse.vorto.codegen.webdevice
        org.eclipse.vorto.codegen.markdown
        org.eclipse.vorto.codegen.ios
        org.eclipse.vorto.codegen.latex
        org.eclipse.vorto.codegen.bosch.things
        org.eclipse.vorto.codegen.coap
        org.eclipse.vorto.codegen.aws
        org.eclipse.vorto.codegen.lwm2m
        org.eclipse.vorto.codegen.prosystfi
        org.eclipse.vorto.codegen.kura
 
 

`

解决方案


这些是 go 中 macintosh 编码的已知别名:

var namemap = map[string]htmlencoding{
    // ...
    "csmacintosh":         macintosh,
    "mac":                 macintosh,
    "macintosh":           macintosh,
    "x-mac-roman":         macintosh,
    // ...
}

由于 macroman 不在该列表中,因此您可以通过设置使用 charsetreader 函数字段来使用自定义别名列表

    decoder.charsetreader = charsetreader

其中 charsetreader 是:

func charsetReader(charset string, input io.Reader) (io.Reader, error) {
    if isCharsetMacintosh(charset) {
        return transform.NewReader(input, charmap.Macintosh.NewDecoder()), nil
    }
    return input, nil
}

var macNames = []string{
    "macroman",
    "csmacintosh",
    "mac",
    "macintosh",
    "x-mac-roman",
}

func isCharsetMacintosh(charset string) bool {
    charset = strings.ToLower(charset)
    for _, n := range macNames {
        if charset == strings.ToLower(n) {
            return true
        }
    }
    return false
}

如果您需要更多信息,此处的答案可能会有所帮助:Unmarshal an ISO-8859-1 XML input in Go。查看 charset.newreaderlabel 函数的源代码并跟踪函数调用也很有帮助。

好了,本文到此结束,带大家了解了《解析XML文件时如何使用MACROMAN编码》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>