ITPub博客

首页 > > > go 解析xml

go 解析xml

作者:nt1979 时间:2019-09-12 09:48:07 0 删除 编辑
package main
import (
    _ "bufio"
    "os"
    "fmt"
    "encoding/xml"
    "io/ioutil"
    "strings"
)
type Property struct {
    Name string
    Value string
    Description string
}
type Configuration struct{
    Property []Property
}
func main(){
    //1.通过读取整个文件来解析xml
    data,err := ioutil.ReadFile("f://core-default.xml")
    res := string(data)
    //将对应的标签字母开头大写 ,因为xml是通过反射解析的,否则无法访问该属性,如果已经大写,则不需替换
    resC := strings.ReplaceAll(res, "configuration>", "Configuration>")
    resP := strings.ReplaceAll(resC, "property>", "Property>")
    resN := strings.ReplaceAll(resP, "name>", "Name>")
    resV := strings.ReplaceAll(resN, "value>", "Value>")
    resD := strings.ReplaceAll(resV, "description>", "Description>")
    //fmt.Println(string(data))
    if err != nil {
        fmt.Println("read file err",err)
    }
    //decoder := xml.NewDecoder(file)
    var conf Configuration
     
    xml.Unmarshal([]byte(resD), &conf)
    //file.Close()
    var cnt int = len(conf.Property)
    fmt.Println("cnt:",cnt)
    fmt.Println(conf)
    //for index ,value := range config.Property{
    //  fmt.Print
    //}
    fmt.Println("----------------------------------------------------------------------")
    fmt.Println("----------------------------------------------------------------------")
    fmt.Println("----------------------------------------------------------------------")
    fmt.Println("----------------------------------------------------------------------")
    fmt.Println("----------------------------------------------------------------------")
    fmt.Println("----------------------------------------------------------------------")
    fmt.Println("----------------------------------------------------------------------")
     
    //通过reader的方式解析xml
    //下面无法替换标签开头为大写,解析失败
    lfile,lerr := os.Open("f://core-default.xml")
     
    if lerr != nil {
        fmt.Println("read file err",err)
    }
    decoder := xml.NewDecoder(lfile)
    var lconf Configuration
    decoder.Decode(lconf)
    lfile.Close()
    fmt.Println(lconf)
     
     
     
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4822/viewspace-3150202/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-05

  • 博文量
    318
  • 访问量
    17304