Use go to parse xml's implementation method of

  • 2020-06-03 06:55:59
  • OfStack

Operating system: CentOS 6.9_x64

go version: 1.8.3

Problem description

There is an automatic barrier reporting program that will automatically send an email to the designated person if a service error occurs. The configuration file is as follows (default.xml) :


<?xml version="1.0" encoding="UTF-8"?>
<config>
  <smtpServer>smtp.163.com</smtpServer>
  <smtpPort>25</smtpPort>
  <sender>user@163.com</sender>
  <senderPasswd>123456</senderPasswd>
  <receivers flag="true">
    <user>Mike_Zhang@live.com</user>
    <user>test1@qq.com</user>
  </receivers>
</config>

This configuration has config as the root tag, xml text part (for example, smtpServer tag), nested xml (receivers tag), xml attribute part (flag for receivers tag), array-like multi-line configuration (user tag), and string and number data types.

The solution


package main

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

type SConfig struct {
  XMLName  xml.Name `xml:"config"` //  Specifies that the outermost tag is config
  SmtpServer string `xml:"smtpServer"` //  read smtpServer Configure the item and save the result to SmtpServer variable 
  SmtpPort int `xml:"smtpPort"`
  Sender string `xml:"sender"`
  SenderPasswd string `xml:"senderPasswd"`
  Receivers SReceivers `xml:"receivers"` //  read receivers The content under the tag is retrieved in a structured manner 
}

type SReceivers struct {
  Flag string `xml:"flag,attr"` //  read flag attribute 
  User []string `xml:"user"` //  read user An array of 
}

func main() {
  file, err := os.Open("default.xml") // For read access.
  if err != nil {
    fmt.Printf("error: %v", err)
    return
  }
  defer file.Close()
  data, err := ioutil.ReadAll(file)
  if err != nil {
    fmt.Printf("error: %v", err)
    return
  }
  v := SConfig{}
  err = xml.Unmarshal(data, &v)
  if err != nil {
    fmt.Printf("error: %v", err)
    return
  }

  fmt.Println(v)
  fmt.Println("SmtpServer : ",v.SmtpServer)
  fmt.Println("SmtpPort : ",v.SmtpPort)
  fmt.Println("Sender : ",v.Sender)
  fmt.Println("SenderPasswd : ",v.SenderPasswd)
  fmt.Println("Receivers.Flag : ",v.Receivers.Flag)
  for i,element := range v.Receivers.User {
    fmt.Println(i,element)
  }
}

Operation effect:


[root@local t1]# ls
default.xml xmlCnfTest1.go
[root@local t1]# go run xmlCnfTest1.go
{{ config} smtp.163.com 25 user@163.com 123456 {true [Mike_Zhang@live.com test1@qq.com]}}
SmtpServer : smtp.163.com
SmtpPort : 25
Sender : user@163.com
SenderPasswd : 123456
Receivers.Flag : true
Mike_Zhang@live.com
test1@qq.com
[root@local t1]#

discuss

If you want to parse the xml configuration directly from a string, replace data with the following statement:


err = xml.Unmarshal(data, &v)

Such as:


err = xml.Unmarshal([]byte(ConfigContent), &v) // ConfigContent for xml string 

Well, that's all. I hope it helped.


Related articles: