首页 > 解决方案 > Prolog 没有进行 XML 解析

问题描述

最近我开始使用 Go。我在解析 XML 时遇到了一个问题。

这是问题:

我能够成功解析以下 XML:

<Root>
<cookie name="e1">hsdhsdhs</cookie>
<cookie name="e2">sssss</cookie>
<cookie name="e3">null</cookie>
<info>
<name>sam</name>
</info>
</Root>

以下是结构:

type Profile struct {
    RootElement xml.Name    `xml:"Root"`
    CookieList  []Cookie    `xml:"cookie"`
    Info        Information `xml:"info"`
}

type Cookie struct {
    Name  string `xml:"name,attr"`
    Value string `xml:",chardata"`
}

type Information struct {
    Name       string `xml:"name"`
}

上面的结构工作正常。

profile := Profile{}
xml.Unmarshal([]byte(xmlString), &profile)
jsonData, _ := json.Marshal(profile)
fmt.Println(string(jsonData))

但是当我在 XML 中保留序言时:

<?xml version="1.0" encoding="EUC-JP"?>
    <Root>
    <cookie name="e1">hsdhsdhs</cookie>
    <cookie name="e2">sssss</cookie>
    <cookie name="e3">null</cookie>
    <info>
    <name>sam</name>
    </info>
    </Root>

然后在打印时,JSON 内没有显示任何数据。

不确定Prolog的问题是什么。

标签: xmlgoxml-parsing

解决方案


在解析非 utf8 xml 文档之前,您必须定义字符集阅读器,这要感谢golang.org/x/net/html/charset您只需替换此字符串:

xml.Unmarshal([]byte(xmlString), &profile)

和:

decoder := xml.NewDecoder(bytes.NewBufferString(xmlString))
decoder.CharsetReader = charset.NewReaderLabel
err := decoder.Decode(&profile)

推荐阅读