2018년 1월 16일 화요일

[GoLaNg] xml parse

1. XML File 내용
<?xml version="1.0" encoding="UTF-8" ?>
<properties>
    <propertie key="HelloMsg">
        <value><![CDATA[Hello World!!]]></value>
    </propertie>
    <propertie key="TestMsg">
        <value><![CDATA[Test!!]]></value>
    </propertie>
</properties>


2. 프로그램
import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "os"

)

/* XML 을 파싱 하기 위한 구조체 */
type Properties struct {
Propertie []Propertie `xml:"propertie"`
}

/* XML 을 파싱 하기 위한 구조체 */
type Propertie struct {
Key   string `xml:"key,attr"`
Value string `xml:"value"`
}

/* XML 파일로 부터 프로퍼티를 읽어 반환 */
func GetPropFromXML(key string) string {
    fp, err := os.Open("freecatz.pe.kr/Conf/properties.xml")
    if err != nil {
        panic(err)
    }
    defer fp.Close()

    // xml 파일 읽기
    data, err := ioutil.ReadAll(fp)

    // xml 디코딩
    var properties Properties
    xmlerr := xml.Unmarshal(data, &properties)
    if xmlerr != nil {
        panic(xmlerr)
    }

    var result string
    for i := 0; i < len(properties.Propertie); i++ {
        if properties.Propertie[i].Key == key {
            result = properties.Propertie[i].Value
        }
        //        fmt.Println("key: " + properties.Propertie[i].Key + "\t -> " + properties.Propertie[i].Value)
    }
    return result
}

댓글 없음 :

댓글 쓰기