gpt4 book ai didi

Prolog 不进行 XML 解析

转载 作者:IT王子 更新时间:2023-10-29 02:00:50 26 4
gpt4 key购买 nike

最近我开始使用 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 中保留 prolog 时:

<?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)

关于Prolog 不进行 XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com