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

Golang中如何将XML转换为结构体 我正在使用 gosoap 包处理 SOAP:https://github.com/tiaguinho/gosoap

我需要将这个 XML 转换为结构体:https://pastebin.com/gMGmWejJ

我尝试了以下方法但没有成功:

type PollResponse struct {
	XMLName xml.Name `xml:"return"`
	User    User     `xml:"user"`
}

type User struct {
	Value []Value `xml:"user"`
}

type Value struct {
	active bool `xml:"active"`
}

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

3 回复

你好

谢谢

brmiha

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


我最近尝试在这个问答中提炼出核心要点:https://stackoverflow.com/questions/53305826/how-to-unmarshal-simple-xml-with-multiple-items-in-go/53305827#53305827。也许这能帮到你。

我还注意到你的Value结构体中的active字段以小写字母开头。

在Go语言中,使用标准库的encoding/xml包可以有效地将XML数据转换为结构体。根据你提供的XML内容,问题主要在于结构体标签定义不正确,导致XML解析失败。以下是修正后的代码示例:

package main

import (
    "encoding/xml"
    "fmt"
)

type PollResponse struct {
    XMLName xml.Name `xml:"return"`
    User    User     `xml:"user"`
}

type User struct {
    Values []Value `xml:"value"`
}

type Value struct {
    Active bool `xml:"active"`
}

func main() {
    xmlData := `
<return>
    <user>
        <value>
            <active>true</active>
        </value>
        <value>
            <active>false</active>
        </value>
    </user>
</return>`

    var response PollResponse
    err := xml.Unmarshal([]byte(xmlData), &response)
    if err != nil {
        panic(err)
    }

    fmt.Printf("User has %d values\n", len(response.User.Values))
    for i, v := range response.User.Values {
        fmt.Printf("Value %d: Active = %t\n", i+1, v.Active)
    }
}

关键修正点:

  1. User结构体中,字段应命名为Values并使用标签xml:"value",因为XML中的元素是<value>
  2. Value结构体中的Active字段首字母必须大写(导出字段),并正确使用标签xml:"active"
  3. 确保所有需要解析的字段都是导出的(首字母大写)

对于你使用的gosoap包,处理SOAP响应时可以这样使用:

import (
    "github.com/tiaguinho/gosoap"
)

func main() {
    soapClient, err := gosoap.SoapClient("your-wsdl-url")
    if err != nil {
        panic(err)
    }

    // 执行SOAP调用
    result, err := soapClient.Call("your-method", map[string]string{})
    if err != nil {
        panic(err)
    }

    var response PollResponse
    err = result.Unmarshal(&response)
    if err != nil {
        panic(err)
    }

    // 使用解析后的数据
    fmt.Printf("Parsed %d user values\n", len(response.User.Values))
}

运行结果应该显示:

User has 2 values
Value 1: Active = true
Value 2: Active = false
回到顶部