解析和生成xml文件 (go)

XML文件

xml文件分为头部和body,
body:<>内容,可以无限嵌套


 
  zhoush.444.com
  3
  [email protected]
  12122
  
   [email protected]
   [email protected]
  
 

go语言实现:

`xml:smtpServer` 中 smtpServer对应的是xml文件中的标签
`xml:"flag,attr"` 中 表示flag是标签的属性,代码中flag即是Receivers的标签属性。
package main

import (
    "encoding/xml"
    "fmt"
    "os"
    "io/ioutil"
)

type config struct {
    XMLName xml.Name `xml:"config"`
    SmtpServer string `xml."smtpServer"`
    SmtpPort string `xml:"smtpPort"`
    Sender string `xml:"sender"`
    SenderPassword string `xml:"senderPassword"`
    Receivers EmailReceivers `xml:"receivers"`
}

type EmailReceivers struct {
    Flag string `xml:"flag,attr"`
    User []string `xml:"user"`
}

func main() {
    v := &config{SmtpServer:"zhoush.444.com",SmtpPort:"3",Sender:"[email protected]",SenderPassword:"12122"}
    v.Receivers.Flag = "true"
    v.Receivers.User = append(v.Receivers.User,"[email protected]")
    v.Receivers.User = append(v.Receivers.User,"[email protected]")
    // v.Lang = append(v.Lang, Language{"Java","http://gogo"})
    // v.Lang = append(v.Lang, Language{"python","http://python"})

    output , err := xml.MarshalIndent(v," "," ")
    if err != nil {
        fmt.Println("error %v", err)
        return
    }
    file, _ := os.Create("config.xml")
    defer file.Close()
    file.Write([]byte(xml.Header))//插入头文件
    file.Write(output)
    OpenXml()
}

func OpenXml(){
    file ,err := os.Open("config.xml")
    if err != nil {
        fmt.Println("open error :", err)
        return
    }
    defer file.Close()

    data, err := ioutil.ReadAll(file)

    if err != nil {
        fmt.Println("error :", err)
        return
    }

    v := config{}
    err = xml.Unmarshal(data, &v)

    if err != nil {
        fmt.Println("error: ", err)
        return
    }
    fmt.Println(v)
}

文件链接

硬链接:将文件的所有属性和内容链接,相当于复制一个文件
软链接:创建文件的快捷方式,

package main

import (
    "fmt"
    "os"
)

func main() {
    os.Chmod("./gogo.txt",0777)
    fp, err := os.Create("./gogo.txt")
    defer fp.Close()

    if err != nil {
        fmt.Println("Create file err :",err)
    }
    // err  = os.Link("gogo.txt","gogo2.txt")//硬链接

    // if err != nil {
    //  fmt.Println( "Link error :", err)
    // }
    err = os.Symlink("gogo.txt","gogo_soft.txt")
    if err != nil {
        fmt.Println(" softlink error", err)
    }
}

你可能感兴趣的:(解析和生成xml文件 (go))