Goはencoding.xml パッケージを使用してXMLや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() {
coffee := &Plant{Id: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}
|
より人間が読みやすい出力を生成するためにMarshalIndent を使用し、当社のプラントを表す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 フィールドタグは、すべてのplant を<parent><child>... の下にネストするようにエンコーダーに指示します。
|
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`
}
|
|
nesting := &Nesting{}
nesting.Plants = []*Plant{coffee, tomato}
|
|
out, _ = xml.MarshalIndent(nesting, " ", " ")
fmt.Println(string(out))
}
|