具有不同属性的相同 XML 标签的不同结构

Different structs for same XML tag with different attributes

假设我有这个 XML:

<something>
  <value type="item">
    ...
  </value>
  <value type="other">
    ...
  </value>
</something>

我能否以某种方式将具有不同属性的值提取到我的结构中的不同项目,例如:

type Something struct {
  Item  Item  `xml:"value[type=item]"` // metacode
  Other Other `xml:"value[type=other]"`
}

可能吗?我应该使用什么作为 xml: 属性?

我认为不可能将按属性值区分的项目列表直接映射到特定字段。您需要将其映射到一个切片,如以下示例(Items 切片):

package main

import (
    "encoding/xml"
    "fmt"
)

func main() {

    type Item struct {
        Type string `xml:"type,attr"`
        Value string `xml:",chardata"`
    }

    type Something struct {
        XMLName xml.Name `xml:"something"`
        Name string `xml:"name"`
        Items []Item `xml:"value"`
    }

    var v Something

    data := `
    <something>
        <name> toto </name>
        <value type="item"> my item </value>
        <value type="other"> my other value </value>
    </something>
    `
    err := xml.Unmarshal([]byte(data), &v)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }

    fmt.Println(v)
}

由您在解码后处理切片以提取值并根据需要将它们放入特定字段。