在线文档  >   Golang练习   >   XML

Go内置支持XML和类似XML的格式,使用encoding.xml包。

package main

import (
    "encoding/xml"
    "fmt"
)

// Plant将被映射到XML。类似于JSON示例,字段标签包含编码器和解码器的指令。
// 这里我们使用XML包的一些特殊功能:XMLName字段名称指定表示此结构体的XML元素的名称;`id,attr`表示Id字段是XML属性而不是嵌套元素。
type Plant struct {
    XMLName xml.Name `xml:"plant"`
    Id      int      `xml:"id,attr"`
    Name    string   `xml:"name"`
    Origin  []string `xml:"origin"`
}

func (p Plant) String() string {
    return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
        p.Id, p.Name, p.Origin)
}

func main() {
    // 创建一个Plant实例
    coffee := &Plant{Id: 27, Name: "Coffee"}
    // 设置Origin字段值为字符串切片
    coffee.Origin = []string{"Ethiopia", "Brazil"}

    // 发出代表我们Plant的XML;使用 MarshalIndent 生成更易读的输出
    // 使用 MarshalIndent 函数将 coffee对象 转换为 XML字节数组
    out, _ := xml.MarshalIndent(coffee, " ", "  ")
    fmt.Println(string(out))

    // 添加通用的XML头部到输出中,在前面显式地添加它
    fmt.Println(xml.Header + string(out))

    // 使用`Unmarshal`将XML字节数组解析为一个数据结构。
    // 如果XML格式错误或无法映射到Plant,则会返回一个描述性错误。
    var p Plant
    if err := xml.Unmarshal(out, &p); err != nil {
        panic(err)
    }
    fmt.Println(p)

    tomato := &Plant{Id: 81, Name: "Tomato"}
    tomato.Origin = []string{"Mexico", "California"}

    // `parent>child>plant` 字段标签告诉编码器将所有植物嵌套在`...`下面
    type Nesting struct {
        // XMLName字段名称指定表示此结构体的XML元素的名称
        XMLName xml.Name `xml:"nesting"`
        // Plants字段是Plant类型的切片,并且有一个嵌套在``下的XML标记
        Plants  []*Plant `xml:"parent>child>plant"`
    }

    nesting := &Nesting{}
    // 将coffee和tomato添加到嵌套结构的Plants字段中
    nesting.Plants = []*Plant{coffee, tomato}
    // 将嵌套结构转换为XML字节数组
    out, _ = xml.MarshalIndent(nesting, " ", "  ")
    fmt.Println(string(out))
}

运行结果如下:

$ go run xml.go
 
   Coffee
   Ethiopia
   Brazil
 

 
   Coffee
   Ethiopia
   Brazil
 
Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
 
   
     
       
         Coffee
         Ethiopia
         Brazil
       
       
         Tomato
         Mexico
         California