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"?>
  <receivers flag="true">

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 (

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)
  defer file.Close()
  data, err := ioutil.ReadAll(file)
  if err != nil {
    fmt.Printf("error: %v", err)
  v := SConfig{}
  err = xml.Unmarshal(data, &v)
  if err != nil {
    fmt.Printf("error: %v", err)

  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 {

Operation effect:

[root@local t1]# ls
default.xml xmlCnfTest1.go
[root@local t1]# go run xmlCnfTest1.go
{{ config} 25 123456 {true []}}
SmtpServer :
SmtpPort : 25
Sender :
SenderPasswd : 123456
Receivers.Flag : true
[root@local t1]#


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: