2018년 1월 18일 목요일

[GoLaNg] xml parse2

1. XML File 내용
<?xml version="1.0" encoding="UTF-8" ?>
<properties>
    <propertie key="HelloMsg"><![CDATA[Hello World!!]]></propertie>
    <propertie key="TestMsg"><![CDATA[Test!!]]></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:",cdata"`
}

/* XML 파일로 부터 프로퍼티를 읽어 반환 */
func GetPropFromXML(key string) string {

    fp, err := os.Open("conf/properties2.xml")
    if err != nil {
        panic(err)
    }
    defer fp.Close()

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

    prop := &Properties{}
    xmlErr := xml.Unmarshal(data, prop)
    if xmlErr != nil {
        fmt.Println(err)
    }
    fmt.Println(prop)
    fmt.Println(len(prop.Propertie))
    var result string
    for i := 0; i < len(prop.Propertie); i++ {
        if prop.Propertie[i].Key == key {
            result = prop.Propertie[i].Value
        }
        //        println("---> " + prop.Propertie[i].Key + "\t -> " + prop.Propertie[i].Value)
    }
    return result

}

댓글 없음 :

댓글 쓰기