How to parse XML data in Go
解析XML数据在Go中非常简单,只需使用内置的encoding/xml包即可。1. 定义带有xml标签的结构体来映射XML元素和属性,如xml:"name"对应子元素,xml:"contact>email"处理嵌套,xml:"id,attr"读取属性;2. 使用xml.Unmarshal将XML字符串解析为结构体;3. 对于文件,使用os.Open打开后通过xml.NewDecoder解码,适合大文件流式处理;4. 处理重复元素时,在结构体中使用切片字段,如[]Person;5. 注意元素名大小写敏感、命名空间处理、可选字段及未知元素的捕获。正确建模结构体后,Go能高效完成XML解析,且推荐小数据用Unmarshal、大数据用Decoder。
Parsing XML data in Go is straightforward thanks to the built-in encoding/xml
package. Whether you're reading from a file, a string, or an HTTP response, Go provides clean ways to unmarshal XML into structs. Here's how to do it effectively.

Define Structs with XML Tags
To parse XML, you first define Go structs that mirror the structure of the XML. Use struct tags with the xml
key to map XML elements and attributes to struct fields.
type Person struct { XMLName xml.Name `xml:"person"` Name string `xml:"name"` Age int `xml:"age"` Email string `xml:"contact>email"` // Nested element Phone string `xml:"contact>phone"` ID string `xml:"id,attr"` // Attribute }
In this example:

xml:"name"
maps to a child element<name>...</name>
xml:"contact>email"
drills into a nested<contact><email>...</email></contact>
xml:"id,attr"
reads theid
attribute from the<person>
tag
Parse XML from a String
Use xml.Unmarshal
to convert XML data into a struct:
package main import ( "encoding/xml" "fmt" "log" ) func main() { data := ` <person id="123"> <name>John Doe</name> <age>30</age> <contact> <email>john@example.com</email> <phone>555-1234</phone> </contact> </person>` var person Person err := xml.Unmarshal([]byte(data), &person) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", person) // Output: {XMLName:{Space: Local:person} Name:John Doe Age:30 Email:john@example.com Phone:555-1234 ID:123} }
Parse XML from a File
To read XML from a file, open it and pass the file reader to xml.NewDecoder
:

package main import ( "encoding/xml" "os" "log" ) func main() { file, err := os.Open("data.xml") if err != nil { log.Fatal(err) } defer file.Close() var person Person decoder := xml.NewDecoder(file) err = decoder.Decode(&person) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", person) }
Using xml.NewDecoder
is memory-efficient for large files since it parses incrementally.
Handle Lists and Repeated Elements
For XML with repeated elements (like a list of users), use slices in your struct:
type Users struct { XMLName xml.Name `xml:"users"` People []Person `xml:"person"` }
With XML like:
<users> <person id="1"><name>Alice</name><age>25</age></person> <person id="2"><name>Bob</name><age>28</age></person> </users>
You can unmarshal it the same way:
var users Users err := xml.Unmarshal([]byte(data), &users) if err != nil { log.Fatal(err) }
Now users.People
will contain two Person
entries.
Tips and Gotchas
- Case sensitivity: XML element names are case-sensitive. Make sure your struct tags match exactly.
-
Namespace handling: If XML uses namespaces, you may need to handle them manually using
xml.Name
or preprocessing. -
Optional fields: Use pointers or
omitempty
-like logic (though it's less common in XML than JSON). -
Unknown elements: You can use
xml:",any"
to capture unknown child elements if needed.
Parsing XML in Go is clean and efficient when you model your structs correctly. Just define the structure, use proper tags, and choose between Unmarshal
for small data and xml.Decoder
for streams or large files.
Basically, it's not complicated — just pay attention to nesting, attributes, and types.
The above is the detailed content of How to parse XML data in Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Using structured logging, adding context, controlling log levels, avoiding logging sensitive data, using consistent field names, correctly logging errors, taking into account performance, centrally monitoring logs and unifying configurations are best practices in Go to achieve efficient logging. First, structured logs in JSON format (such as using uber-go/zap or rs/zerolog) facilitate machine parsing and integrating ELK, Datadog and other tools; second, log traceability is enhanced by requesting context information such as ID and user ID, and can be injected through context.Context or HTTP middleware; third, use Debug, Info, Warn, Error levels reasonably, and operate through environment variables.

Usesignal.Notify()tolistenforSIGINT/SIGTERMandtriggershutdown;2.RuntheHTTPserverinagoroutineandblockuntilasignalisreceived;3.Callserver.Shutdown()withacontexttimeouttostopacceptingnewrequestsandallowin-flightonestocomplete;4.Propagatetheshutdownconte

InGo,atypeimplementsaninterfaceimplicitlybyprovidingallrequiredmethodswithoutexplicitdeclaration.1.Interfacesaresatisfiedautomaticallywhenatypehasmethodsmatchingtheinterface'ssignatureexactly.2.No"implements"keywordisneeded—ducktypingisused

Using multi-process parallel parsing of independent XML files can significantly improve performance. 1. Prioritize ProcessPoolExecutor to avoid GIL restrictions; 2. Ensure files are independent or processed in chunks of large files; 3. Use efficient parsing libraries such as lxml; 4. Limit concurrency number to prevent system overload; 5. Ensure fault tolerance through exception capture, and ultimately achieve safe and efficient parallel parsing.

Parsing XML data is very simple in Go, just use the built-in encoding/xml package. 1. Define a structure with xml tag to map XML elements and attributes, such as xml:"name" corresponding child elements, xml:"contact>email" handles nesting, xml:"id, attr" reads attributes; 2. Use xml.Unmarshal to parse XML strings into structures; 3. For files, use os.Open to open them and decode them through xml.NewDecoder, which is suitable for streaming processing of large files; 4. When processing duplicate elements, in the structure

Usetime.Now()togetthecurrentlocaltimeasatime.Timeobject;2.FormatthetimeusingtheFormatmethodwithlayoutslike"2006-01-0215:04:05";3.GetUTCtimebycallingUTC()ontheresultoftime.Now();4.Extractcomponentslikeyear,month,dayusingmethodssuchasYear(),M

Use io.Reader and io.Writer to efficiently stream data to avoid memory overflow; use io.Copy to realize blocked transmission of files, HTTP or network data; use goroutines and channels to build processing pipelines, such as reading large log files line by line; use io.Pipe to safely transfer data between goroutines; always read and write in blocks to avoid loading all data at once, and ensure that memory is controllable.

Go code performance analysis can be implemented through the built-in pprof tool. First, import the debug endpoint to enable the \_"net/http/pprof"; 1. For HTTP services, start the pprof interface of localhost:6060 in the program; 2. Use gotoolpprof http://localhost:6060/debug/pprof/profile?seconds=30 to collect 30 seconds CPU performance data; 3. Analyze the memory allocation through gotoolpprof http://localhost:6060/debug/pprof/heap; 4. Enable run
