Home > Backend Development > Golang > golang array to xml

golang array to xml

PHPz
Release: 2023-05-10 09:48:37
Original
687 people have browsed it

As golang becomes increasingly popular in the fields of web development and cloud computing, golang's xml processing has gradually received attention. In actual projects, we often need to transmit and store data in xml format, and we also need to parse the data from xml and convert it into a go array. Therefore, this article will introduce how to convert go arrays into xml format and use it in actual development.

1. Golang’s xml package

Golang’s xml package is the core package for processing xml. It provides parsing from xml to go data structure and from go data structure to xml. Serialization function. Golang's xml package supports encoding and decoding of various types such as structures, numbers, and strings. Among the functions provided by this package, the Marshal and Unmarshal functions are the two most commonly used functions, which are used to serialize and parse xml data respectively.

2. Array to xml

Although golang's xml package supports encoding and decoding of various types, it does not provide a corresponding interface for the serialization and deserialization of arrays. Therefore, when encoding and decoding xml arrays, we need to define the conversion method ourselves.

  1. Convert array to xml

Our idea of ​​converting an array into xml format is: first convert the array into a structure, and then convert the structure into xml. Next, we first define a custom type User, which has three fields: id, name, and age.

type User struct {
    Id   string `xml:"id"`
    Name string `xml:"name"`
    Age  int    `xml:"age"`
}
Copy after login

Then define a Users data type, which also has three fields, namely XMLName, Version and user array Items.

type Users struct {
    XMLName xml.Name `xml:"users"`
    Version string   `xml:"version,attr"`
    Items   []User   `xml:"user"`
}
Copy after login

Next, we define a function to convert the array into xml format. The basic idea of ​​this function is to create an instance of the Users type, convert each element in the array to the User type, and add it to the Items array of Users. Finally, use the xml.Marshal function to convert the Users instance into bytes in xml format. array.

func ArrayToXml(arr []interface{}) ([]byte, error) {
    var users Users
    users.Version = "1.0"
    for i := 0; i < len(arr); i++ {
        var user User
        if v, ok := arr[i].(map[string]interface{}); ok {
            user.Id = v["id"].(string)
            user.Name = v["name"].(string)
            user.Age = v["age"].(int)
            users.Items = append(users.Items, user)
        }
    }
    return xml.Marshal(users)
}
Copy after login

In the above code, the variable arr refers to an array of any type, and each element of it is of type map[string]interface{}. Type assertions are used here to force variables of the map[string]interface{} type into the corresponding type to achieve parsing of elements in the array.

  1. Xml to array

The same as converting an array to xml, the idea of ​​converting xml to an array is: first convert the xml into a structure, and then convert the structure Convert to an array of corresponding type.

The Unmarshal function is provided in golang's xml package, which can convert a byte array in xml format into a structure. The following code shows how to convert a byte array in xml format into a Users instance:

func XmlToArray(data []byte) ([]interface{}, error) {
    var users Users
    var arr []interface{}
    err := xml.Unmarshal(data, &users)
    if err != nil {
        return nil, err
    }
    for _, item := range users.Items {
        m := make(map[string]interface{})
        m["id"] = item.Id
        m["name"] = item.Name
        m["age"] = item.Age
        arr = append(arr, m)
    }
    return arr, nil
}
Copy after login

In the above code, we convert the Users type instance parsed from xml into an array type. A for loop is used here to convert each User type instance in the Users instance to the map[string]interface{} type and add it to the array.

3. Test

We have successfully implemented the basic operations of converting arrays into xml format and converting xml format into arrays. Let’s do a test:

func main() {
    arr := make([]interface{}, 0)
    m1 := map[string]interface{}{
        "id":   "1",
        "name": "Tom",
        "age":  20,
    }
    m2 := map[string]interface{}{
        "id":   "2",
        "name": "Jerry",
        "age":  22,
    }
    arr = append(arr, m1)
    arr = append(arr, m2)

    data, err1 := ArrayToXml(arr)
    if err1 != nil {
        fmt.Println("error:", err1)
        return
    }
    fmt.Println("array to xml:", string(data))

    arr2, err2 := XmlToArray(data)
    if err2 != nil {
        fmt.Println("error:", err2)
        return
    }
    fmt.Println("xml to array:", arr2)
}
Copy after login

Running the above code, we can see the following results:

array to xml: <?xml version="1.0" encoding="UTF-8"?>
<users version="1.0">
    <user>
        <id>1</id><name>Tom</name><age>20</age>
    </user>
    <user>
        <id>2</id><name>Jerry</name><age>22</age>
    </user>
</users>

xml to array: [map[id:1 name:Tom age:20] map[id:2 name:Jerry age:22]] 
Copy after login

It means that we successfully converted the array into xml format and can correctly parse the xml format data into an array of the corresponding type.

4. Summary

This article mainly introduces how to use golang's xml package to convert arrays into xml format and convert xml format into arrays. Although golang's xml package itself does not provide corresponding support for arrays, we can serialize and deserialize arrays by converting arrays into structures and converting structures into xml. In actual projects, we need to carry out customized development according to specific needs and continuously improve and optimize the interface to achieve better usage results.

The above is the detailed content of golang array to xml. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template