Home > Article > Backend Development > Use the functions provided by the encoding/xml package to encode and decode XML, and set the indentation format
Use the encoding/xml package to encode and decode XML, and set the indentation format
In the Go language, the encoding/xml package provides a series of functions to encode and decode XML. These functions can help us convert structure data in Go language to data in XML format, and can also convert data in XML format into structure data in Go language. At the same time, we can also make the generated XML more readable by setting the indentation format.
Before encoding and decoding XML, we first need to define a structure to represent the data we want to convert. For example, we define a Person structure as follows:
type Person struct { Name string `xml:"name"` Age int `xml:"age"` Address string `xml:"address"` }
Next, we can use the xml.MarshalIndent function to encode the structure into an XML string and set the indentation format. The example is as follows:
func main() { p := &Person{ Name: "Alice", Age: 25, Address: "123 Main St", } xmlData, err := xml.MarshalIndent(p, "", " ") if err != nil { fmt.Println("XML encoding error:", err) return } fmt.Println(string(xmlData)) }
In the above example, we encode the Person structure into XML format data through the xml.MarshalIndent function, and set the indent format to 4 spaces. Finally, we use the fmt.Println function to print out the generated XML string.
The output results are as follows:
<Person> <name>Alice</name> <age>25</age> <address>123 Main St</address> </Person>
By setting the indentation format, the generated XML data is easier to read and understand.
In addition to encoding, we can also use the xml.Unmarshal function to decode XML format data into structure data in the Go language. The example is as follows:
func main() { xmlData := []byte(` <Person> <name>Alice</name> <age>25</age> <address>123 Main St</address> </Person> `) var p Person err := xml.Unmarshal(xmlData, &p) if err != nil { fmt.Println("XML decoding error:", err) return } fmt.Println("Name:", p.Name) fmt.Println("Age:", p.Age) fmt.Println("Address:", p.Address) }
In the above example, we first define an XML format data, and then use the xml.Unmarshal function to decode the XML data into Person structure data. Finally, we print the decoded data using the fmt.Println function.
The output results are as follows:
Name: Alice Age: 25 Address: 123 Main St
Through the functions provided by the encoding/xml package, we can easily encode and decode XML, and we can set the indentation format to make the generated XML more beautiful and visible. read. These functions provide a simple yet powerful way to process XML data.
The above is the detailed content of Use the functions provided by the encoding/xml package to encode and decode XML, and set the indentation format. For more information, please follow other related articles on the PHP Chinese website!