Golang中如何将XML转换为结构体

Golang中如何将XML转换为结构体 我有以下与产品线详情相关的XML数据:

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"`
}
<iq from="s.whatsapp.net" id="79.242-3" type="result">
  <order creation_ts="1651699388" id="368282458424984">
    <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=OMyHhkGxzRoAX-9cHVL&_nc_ad=z-m&_nc_cid=0&_nc_ht=mmg.whatsapp.net&oh=01_AVxAZgz_LwkteWpkZhK26OLEZFrg3GTx-cMJP_h8V_vmJQ&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)
				}

但是没有成功!

Go Playground链接:Go Playground - The Go Programming Language


更多关于Golang中如何将XML转换为结构体的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

没有成功,我添加了游乐场链接:Go Playground - The Go Programming Language

更多关于Golang中如何将XML转换为结构体的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


错误信息是什么?

hyousef:

iq := &Iq{}

你可能想要的是 var iq Iq。你的 iq 是一个指向 Iq 的指针,然后你将指向该指针的指针传递给了 Unmarshal

您的URL标签是无效的XML,因为它包含字面量 & 字符。请将它们替换为 &amp; Go Playground - The Go Programming Language

Beware of the ampersand when using XML

XML文档是表示信息的一种绝佳方式。但某些字符,例如“与”符号(&),可能会带来问题,因为它们具有特殊含义。以下是如何避免由“与”符号和其他特殊字符带来的陷阱。

预计阅读时间:3分钟

在Go中解析XML时,结构体标签必须与XML结构完全匹配。你的XML包含order元素的属性(creation_tsid),但你的结构体没有定义这些字段。此外,pricecurrency字段在product中重复出现,但在XML中它们位于不同层级。

以下是修正后的结构体定义:

package main

import (
    "encoding/xml"
    "fmt"
)

type Catalog struct {
    XMLName xml.Name `xml:"catalog"`
    Id      string   `xml:"id"`
}

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

type Image struct {
    XMLName xml.Name `xml:"image"`
    Url     string   `xml:"url"`
    Id      int      `xml:"id"`
}

type Product struct {
    XMLName    xml.Name `xml:"product"`
    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 {
    XMLName    xml.Name `xml:"order"`
    CreationTS string   `xml:"creation_ts,attr"`
    Id         string   `xml:"id,attr"`
    Product    Product  `xml:"product"`
    Catalog    Catalog  `xml:"catalog"`
    Price      Price    `xml:"price"`
}

type Iq struct {
    XMLName xml.Name `xml:"iq"`
    From    string   `xml:"from,attr"`
    Id      string   `xml:"id,attr"`
    Type    string   `xml:"type,attr"`
    Order   Order    `xml:"order"`
}

func main() {
    xmlData := `<iq from="s.whatsapp.net" id="79.242-3" type="result">
  <order creation_ts="1651699388" id="368282458424984">
    <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=OMyHhkGxzRoAX-9cHVL&_nc_ad=z-m&_nc_cid=0&_nc_ht=mmg.whatsapp.net&oh=01_AVxAZgz_LwkteWpkZhK26OLEZFrg3GTx-cMJP_h8V_vmJQ&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(xmlData), iq)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Parsed XML:\n")
    fmt.Printf("IQ From: %s\n", iq.From)
    fmt.Printf("Order ID: %s\n", iq.Order.Id)
    fmt.Printf("Product Name: %s\n", iq.Order.Product.Name)
    fmt.Printf("Total Price: %d %s\n", iq.Order.Price.Total, iq.Order.Price.Currency)
}

关键修改:

  1. 为所有结构体添加了XMLName字段以明确XML元素名称
  2. Order结构体中添加了CreationTSId字段,使用attr标签捕获XML属性
  3. Iq结构体中添加了FromIdType字段,同样使用attr标签
  4. 修正了结构体名称使用大写字母开头(Go的导出规则)

运行此代码将正确解析XML数据。

回到顶部