SoFunction
Updated on 2025-03-05

Implementation method of parsing XML using go language (must read)

Operating system: CentOS 6.9_x64

Go language version: 1.8.3

Problem description

There is an automatic failure report program. If a service error occurs, it will automatically send an email to the designated person. The configuration file content is as follows ():

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

This configuration takes config as the root tag, with xml text part (such as smtpServer tag), nested xml (receivers tag), xml attribute part (receivers tag flag), array-like multi-line configuration (user tag), and data types are two types: string and number.

Solution

package main

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

type SConfig struct {
  XMLName   `xml:"config"` // Specify the outermost label as config  SmtpServer string `xml:"smtpServer"` // Read the smtpServer configuration item and save the result to the SmtpServer variable  SmtpPort int `xml:"smtpPort"`
  Sender string `xml:"sender"`
  SenderPasswd string `xml:"senderPasswd"`
  Receivers SReceivers `xml:"receivers"` // Read the content under the receivers tag and obtain it in a structural manner}

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

func main() {
  file, err := ("") // For read access.
  if err != nil {
    ("error: %v", err)
    return
  }
  defer ()
  data, err := (file)
  if err != nil {
    ("error: %v", err)
    return
  }
  v := SConfig{}
  err = (data, &amp;v)
  if err != nil {
    ("error: %v", err)
    return
  }

  (v)
  ("SmtpServer : ",)
  ("SmtpPort : ",)
  ("Sender : ",)
  ("SenderPasswd : ",)
  (" : ",)
  for i,element := range  {
    (i,element)
  }
}

Running effect:

[root@local t1]# ls
 
[root@local t1]# go run 
{{ config} smtp. 25 user@ 123456 {true [Mike_Zhang@ test1@]}}
SmtpServer : smtp.
SmtpPort : 25
Sender : user@
SenderPasswd : 123456
 : true
Mike_Zhang@
test1@
[root@local t1]#

discuss

If you need to parse the xml configuration directly from the string, you can replace the data in the following statement:

err = (data, &v)

for example:

err = ([]byte(ConfigContent), &amp;v) // ConfigContentforxmlString

OK, that's all, I hope it will be helpful to you.

The above article is the implementation method of parsing XML using Go language (must-read) which is shared with you by the editor. I hope it can give you a reference and I hope you can support me more.