xml - 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的问题是什么。
解决方案
在解析非 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)
推荐阅读
- python - pd.to_datetime() 与西班牙语言环境系统
- python - 为什么 Web3.py 交易功能不起作用?
- c# - 如何通过 IIS 使用打印机
- python - 如何在 Python 中使用 GUI Tkinter 以特定格式显示来自数据库 sqlite3 的信息?
- php - GitLab CI/CD - 学说/dbal 和 laminas/laminas-code PHP 版本问题
- authorize.net - 为 Dotnet Core 授权.Net SDK
- python - How to create this type of relationship using Django Models
- javascript - Use promised getter in VueRouter beforeEach
- r - 如何从 R 中列出的模型中提取参数?
- c# - Amazon.Lambda.Serialization.Json.JsonSerializer 是否尊重 JsonIgnore