반응형

간단하게 API 호출을 하는 프로그램을 개발해달라는 요청이 있어서, 고민하던 중 Windows / Linux 둘다 돌아가야 하겠고,

여러번 귀찮게 작업 안할 수 있고, 심플하게 개발할 수 있는 Go lang을 선택했다.


다만, 구시대 유물과 같은 XML 기반 서버와의 통신을 해야되는 상황이라, 마샬링과 언마샬링에서 삽질을 조금 했다.


1. Marshal

아래와 같은 데이터를 마샬링할 예정이다.



    aaaaa

    eeee



struct를 생성할 때, 생성할 xml에 대한 meta정보를 넣어주는 것만으로 가능하다. 

package main

import (
	"encoding/xml"
	"fmt"
)

type test struct {
	XMLName xml.Name `xml:"test"`
	Abc     abc      `xml:"abc"`
	Eee     string   `xml:"eee"`
}

type abc struct {
	Key   string `xml:"name,attr"`
	Value string `xml:",chardata"`
}

func main() {
	a := &abc{Key: "tester", Value: "aaaaa"}
	v := &test{Abc: *a, Eee: "eeee"}

	output, err := xml.Marshal(v)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(string(output))
}


2. UnMarshal

위에 만든 데이터를 그대로, 언마샬링 해본다.

package main

import (
	"encoding/xml"
	"fmt"
)

type test struct {
	XMLName xml.Name `xml:"test"`
	Abc     abc      `xml:"abc"`
	Eee     string   `xml:"eee"`
}

type abc struct {
	Key   string `xml:"name,attr"`
	Value string `xml:",chardata"`
}

func main() {
	a := &abc{Key: "tester", Value: "aaaaa"}
	v := &test{Abc: *a, Eee: "eeee"}

	output, err := xml.Marshal(v)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(string(output))

	var t test
	err = xml.Unmarshal(output, &t)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(t)
}


attr, chardata 등을 잘 활용하면, xml 데이터를 손쉽게 다룰 수 있는 것 같다.

추가로 xml.Name이 struct 변수에서 생략된 경우, struct Name으로 자동인식하게 된다.

반응형

'개발 > Go' 카테고리의 다른 글

[Go] set timezone  (0) 2016.06.28
[Go] func 가변인자(dynamic arguments) 전달  (0) 2016.06.28
[Go] SyntaxHighlighter  (0) 2016.06.28
[Go] LumberJack for Logging  (0) 2016.06.28
[개발환경] Go + SubLimeText 3 + GoSublime  (0) 2016.06.11
,