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

时间:2015-02-04 01:23:37

标签: xml struct go

我们说我有这个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:属性?

1 个答案:

答案 0 :(得分:1)

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

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

在解码后处理切片以提取值并在需要时将它们放在特定字段中。

相关问题