go xml 解析一

  • xml
<?xml version="1.0" encoding="UTF-8"?>
<Persons>
    <Person>
        <Name>小王</Name>
        <Age>28</Age>
        <Career>无业游民</Career>
        <Interests>
            <Interest>编程</Interest>
            <Interest>下棋</Interest>
        </Interests>
    </Person>
    <Person>
        <Name>小明</Name>
        <Age>27</Age>
        <Career>码农</Career>
        <Interests>
            <Interest>编程</Interest>
            <Interest>下棋</Interest>
        </Interests>
    </Person>
</Persons>

 

  • xmlModel
/**
* @Author: wsp
* @Date: 2018/1/12 9:37
* @Description:
 */
package xml

type Result struct {
    Person []Person
}

type Person struct {
    Name      string
    Age       string
    Career    string
    Interests Interests
}

type Interests struct {
    Interest []string
}
  • xmlAnalyze
/**
* @Author: wsp
* @Date: 2018/1/11 15:16
* @Description:
 */
package xml

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "unicontract-validate/utils/jsonUtils"
)

/**
* @Author: wsp
* @Date: 9:38 2018/1/12
* @Description: 测试xml
 */
func XmlTest1() {
    content, err := ioutil.ReadFile("test.xml")
    ErrHandler(err)
    //fmt.Println("xml中内容:")
    //fmt.Println(string(content))

    // xml 解析到result的结构中
    var result Result
    err2 := xml.Unmarshal(content, &result)
    ErrHandler(err2)
    fmt.Println("xml解析后的内容:")
    fmt.Println(result)

    // sturct to json
    jsonString, err3 := jsonUtils.ConvertResultToJsonString(result)
    ErrHandler(err3)
    fmt.Println("struct to json:")
    fmt.Println(jsonString)

}

/**
* @Author: wsp
* @Date: 10:27 2018/1/12
* @Description: 错误处理
 */
func ErrHandler(err error) {
    if err != nil {
        panic(err)
    }
}
  • jsonUtils
/**
* @Author: wsp
* @Date: 2018/1/10 18:05
* @Description:
 */
package jsonUtils

import (
    "encoding/json"
    "unicontract-validate/common/uniledgerLogger"
)

/**
* @Author: wsp
* @Date: 18:18 2018/1/10
* @Description: 将返回值转换为json串返回
* @Param: Result结构
* @Return: json串,err
 */
func ConvertResultToJsonString(param interface{}) (string, error) {
    result, err := json.Marshal(param)
    if err != nil {
        uniledgerLogger.Error("返回结果struct转json出错:", err)
    }
    return string(result), err
}

 

  • result
xml解析后的内容:
{[{小王 28 无业游民 {[编程 下棋]}} {小明 27 码农 {[编程 下棋]}}]}
struct to json:
{"Person":[{"Name":"小王","Age":"28","Career":"无业游民","Interests":{"Interest":["编程","下棋"]}},{"Name":"小明","Age":"27","Career":"码农","Interests":{"Interest":["编程","下棋"]}}]}

 

posted @ 2018-01-12 13:07  穷开心y  阅读(5031)  评论(2编辑  收藏  举报