xml - 什么是无效字符实体 &ccb

标签 xml go

我有这个 Playground :https://go.dev/play/p/uEpYEWaQaV0 但没有得到什么问题,为什么它不工作!我得到了错误:

invalid character entity &ccb

我的代码是:

package main

import (
    "encoding/xml"
    "fmt"
)

type catalog struct {
    Id string `xml:"id"`
}

type price struct {
    Subtotal    int    `xml:"subtotal"`
    Currency    string `xml:"currency"`
    Total       int    `xml:"total"`
    PriceStatus string `xml:"price_status"`
}

type image struct {
    Url string `xml:"url"`
    Id  int    `xml:"id"`
}

type product struct {
    Id         int    `xml:"id"`
    RetailerId int    `xml:"retailer_id"`
    Image      image  `xml:"image"`
    Price      int    `xml:"price"`
    Currency   string `xml:"currency"`
    Name       string `xml:"name"`
    Quantity   int    `xml:"quantity"`
}

type order struct {
    Product product `xml:"product"`
    Catalog catalog `xml:"catalog"`
    Price   price   `xml:"price"`
}

type Iq struct {
    XMLName xml.Name `xml:"iq"`
    Order   order    `xml:"order"`
}

func main() {
    contents := `<iq from="s.whatsapp.net" id="162.120-3" type="result">
  <order creation_ts="1651703902" id="1046755402590219">
    <product>
      <id>8312993582051445</id>
      <retailer_id>291</retailer_id>
      <image>
        <url>https://mmg.whatsapp.net/v/t45.5328-4/279646282_7510595942346471_4295336878174066544_n.jpg?stp=dst-jpg_p100x100&ccb=1-5&_nc_sid=c48759&_nc_ohc=OMyHhkGxzRoAX8Dn93Q&_nc_ad=z-m&_nc_cid=0&_nc_ht=mmg.whatsapp.net&oh=01_AVw_0loIIuK1LP-n5OL1hdpRmNYhAiUjLGk20FCclgNXCA&oe=62774C93</url>
        <id>7510595939013138</id>
      </image>
      <price>5000</price>
      <currency>SAR</currency>
      <name>coffee</name>
      <quantity>1</quantity>
    </product>
    <catalog><id>326185462964376</id></catalog>
    <price>
      <subtotal>5000</subtotal>
      <currency>SAR</currency>
      <total>5000</total>
      <price_status>provided</price_status>
    </price>
  </order>
</iq>`

    iq := &Iq{}

    err := xml.Unmarshal([]byte(contents), &iq)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", iq.Order)
}

最佳答案

@collapsar 的回答为基础...

尽管 XML 格式错误,您仍然可以通过创建 Decoder 实例并关闭 Strict 模式来处理它:

d := xml.NewDecoder(bytes.NewReader([]byte(contents)))
d.Strict = false
err := d.Decode(&iq)
if err != nil {
    panic(err)
}
fmt.Printf("%v\n", iq.Order)

Go Playground

引用见https://pkg.go.dev/encoding/xml#Decoder .

关于xml - 什么是无效字符实体 &ccb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72120226/

相关文章:

python - 使用 BeautifulSoup 从表中提取某些列

java - xml bean配置到java代码配置

xml - 命名空间 'http://exslt.og/common' 错误

postgresql - 如何获取 Golang 数据库连接池来管理集群中多台主机的连接?

IntelliJ 中的 Go 项目不解决依赖关系

oracle - 戈朗oci8 : error adding symbols: File in wrong format

go - 将 IPMask 转换为 IPAddr

go - 我应该如何构建一个简单的 Go 项目?

Android-是否可以在字符串资源中添加可点击的链接

java - 更改 editText 字段内的可绘制图像