Table of Contents
1. Import the XML package
2. Create XML structure
3. Parse the XML into the structure
4. Marshall the structure into XML
5. Manipulate XML elements
6. Summary
Home Backend Development Golang How to use XML in Go?

How to use XML in Go?

May 11, 2023 pm 04:04 PM
go language (go) xml parsing libraries

XML is a common data exchange format. In Go language, there are many ways to manipulate XML. Here's how to use XML in Go.

1. Import the XML package

First, you need to import the encoding/xml standard library into the Go program.

import "encoding/xml"
Copy after login

2. Create XML structure

In Go, structures are used to represent XML data. Here is a sample XML as an example.

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J.K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
Copy after login

You can create the following Go structure to represent it:

type Bookstore struct {
    XMLName xml.Name `xml:"bookstore"`
    Books   []Book   `xml:"book"`
}

type Book struct {
    XMLName xml.Name `xml:"book"`
    Category  string    `xml:"category,attr"`
    Title  string    `xml:"title"`
    Author string    `xml:"author"`
    Year   int       `xml:"year"`
    Price  float32   `xml:"price"`
}
Copy after login

3. Parse the XML into the structure

Then, you can use xml.Unmarshal( )Function parses XML data into Go structure.

xml_data := []byte(`<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J.K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>`)

var bookstore Bookstore
err := xml.Unmarshal(xml_data, &bookstore)
if err != nil {
    fmt.Println("error: ", err)
    return
}

fmt.Println(bookstore)
Copy after login

xml.Unmarshal()Parses XML data into a structure and stores the result in the bookstore variable.

4. Marshall the structure into XML

Conversely, you can use the xml.Marshal() function to marshal the structure into XML data.

bookstore := Bookstore {
    XMLName: xml.Name{Local: "bookstore"},
    Books: []Book{
        Book{
            Category: "children",
            Title:    "Harry Potter",
            Author:   "J.K. Rowling",
            Year:     2005,
            Price:    29.99,
        },
        Book{
            Category: "web",
            Title:    "Learning XML",
            Author:   "Erik T. Ray",
            Year:     2003,
            Price:    39.95,
        },
    },
}

xml_data, err := xml.MarshalIndent(bookstore, "", "  ")
if err != nil {
    fmt.Println("error: ", err)
}
fmt.Printf("%s
", xml_data)
Copy after login

xml.MarshalIndent()The function marshals the bookstore structure into XML data and stores the result in the variable xml_data. The first parameter is the structure to be grouped, the second parameter is the indented string to be used before each line, and the third parameter is the string to be used between each element.

5. Manipulate XML elements

In the structure, you can use XML names (such as <book>) and XML attributes (such as category) as the label of the structure field.

type Book struct {
    XMLName xml.Name `xml:"book"`
    Category string `xml:"category,attr"`
    Title    string `xml:"title"`
    Author   string `xml:"author"`
    Year     int    `xml:"year"`
    Price    int    `xml:"price"`
}
Copy after login

When parsing XML, the values ​​of the structure fields will be automatically populated based on the XML data.

6. Summary

Use the above steps to use XML in Go. First, you need to import the encoding/xml library, and then define a structure to represent XML data. XML data can be parsed into this structure, or this structure can be used to marshal XML data. To operate XML elements, you need to use the name and attributes of the XML element in the structure field tag.

The above is the detailed content of How to use XML in Go?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to process and operate the parsing and generation of XML data types in PHP How to process and operate the parsing and generation of XML data types in PHP Jul 15, 2023 pm 01:45 PM

PHP is a commonly used server-side scripting language that is widely used in the field of web development. In the process of web development, it is often necessary to process and operate XML data types, such as parsing and generating XML files. This article will introduce how to process and operate XML data types in PHP, and provide relevant code examples. 1. Parse XML data Parsing XML data is the process of converting XML files into data structures in PHP. In PHP, you can use SimpleXML or DOMDocument class to parse

How to use constants in Go? How to use constants in Go? May 11, 2023 pm 04:52 PM

In Go, constants are identifiers that maintain a fixed value and do not change throughout the execution of the program. Constants in Go are declared using the const keyword. In this article, we will explore how to use constants in Go. How to declare a constant Declaring a constant in Go is very simple, just use the const keyword. The format is as follows: constidentifier[type]=value where identifier is the constant name

How to implement route grouping in Go language How to implement route grouping in Go language Dec 17, 2023 pm 11:09 PM

Go language is a simple and efficient programming language that is also widely used in the field of web development. In web development, routing is an essential part. Routing grouping is a more advanced routing function, which can make the code clearer and concise, and improve the readability and maintainability of the code. This article will introduce in detail how to implement routing grouping in Go language from both the principle and code implementation aspects. 1. Principle of grouping Routing grouping is equivalent to grouping and managing some routes with similar characteristics. For example, we can convert all APIs

Practical experience: best practices in Go language development projects Practical experience: best practices in Go language development projects Nov 02, 2023 pm 01:07 PM

Abstract: This article mainly introduces the best practices in Go language development projects. By explaining the experience in project structure design, error handling, concurrency processing, performance optimization and testing, it helps developers better cope with challenges in actual projects. 1. Design of project structure Before starting a Go language project, a good project structure design is crucial. A good project structure can improve team collaboration efficiency and better manage the project's code and resources. Here are some best practices for project structure: Separate code as much as possible

How to use Go language for code parallelization practice How to use Go language for code parallelization practice Aug 02, 2023 am 09:12 AM

How to use Go language for code parallelization practice In modern software development, performance is a very important consideration. In order to improve code execution efficiency, we can use parallel programming technology. As a concurrent programming language, Go language has a wealth of parallelization tools and features that can help us achieve good parallelization of code. This article will introduce how to use Go language for code parallelization practice, starting from basic concurrency processing to complex parallel algorithm optimization. Basic Concurrency Processing Concurrency processing refers to executing multiple tasks at the same time.

How to optimize JSON serialization and deserialization in Go language development How to optimize JSON serialization and deserialization in Go language development Jul 01, 2023 pm 09:01 PM

How to optimize JSON serialization and deserialization in Go language development. In Go language development, JSON (JavaScriptObjectNotation) is a frequently used serialization and deserialization format. It's concise, readable, and easy to interact with across different platforms. However, when processing large data or high concurrency scenarios, JSON serialization and deserialization performance may become a performance bottleneck. This article will introduce some optimization methods for JSON serialization and deserialization in Go language development.

Methods to solve memory leaks in Go language Websocket applications Methods to solve memory leaks in Go language Websocket applications Dec 14, 2023 pm 01:46 PM

The method to solve the memory leak of Go language Websocket application requires specific code examples. Websocket is a protocol that implements full-duplex communication on the network and is often used for real-time data transmission and push. In Go language, we can write Websocket applications by using the WebSocket module in the standard library net/http. However, when developing Websocket applications, we may encounter memory leaks, resulting in application performance degradation or even

How does the garbage collection mechanism work in Go language? How does the garbage collection mechanism work in Go language? Jun 10, 2023 am 08:55 AM

Go language is an open source statically typed programming language developed by Google and debuted in 2009. It is characterized by simple syntax, high performance, convenient concurrent programming, etc., so it is loved by more and more programmers. In the Go language, there is generally no need to manually manage memory because it provides a garbage collection mechanism that can automatically manage memory. So, how does the garbage collection mechanism in Go language work? This article will introduce it to you. Garbage collection in Go language

See all articles