

[Golang] XML Parsing Example (3)
source link: http://siongui.github.io/2015/02/21/go-parse-xml-example-3/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Golang] XML Parsing Example (3)
February 21, 2015
In this exmaple, we will parse a div element with a span child element,
<span>SpanText</span>
:
example-3.xml | repository | view raw
<?xml version="1.0" encoding="UTF-8"?><div><span>SpanText</span></div>
Just as we declare a struct for parent div element, we also declare a struct for the child span element, and add a struct field of the span struct to the div struct.
parse-3.go | repository | view raw
package main import ( "io/ioutil" "encoding/xml" "fmt" ) type div struct { XMLName xml.Name `xml:"div"` ChildSpan span } type span struct { XMLName xml.Name `xml:"span"` Text string `xml:",chardata"` } func main() { d := div{} xmlContent, _ := ioutil.ReadFile("example-3.xml") err := xml.Unmarshal(xmlContent, &d) if err != nil { panic(err) } fmt.Println("ChildSpan:", d.ChildSpan) }
The output result:
ChildSpan: {{ span} SpanText}
Tested on: Ubuntu Linux 14.10, Go 1.4.
[Golang] XML Parsing Example series:
[1][Golang] XML Parsing Example (1)
[2][Golang] XML Parsing Example (2)
[3][Golang] XML Parsing Example (3)
[4][Golang] XML Parsing Example (4)
[5][Golang] XML Parsing Example (5) - Parse OPML
[6][Golang] XML Parsing Example (6) - Parse OPML Concisely
[7][Golang] XML Parsing Example (7) - Parse RSS 2.0
[8][Golang] XML Parsing Example (8) - Parse Atom 1.0
[9][Golang] Convert Atom to RSS
[10][Golang] Parse Web Feed - RSS and Atom
Recommend
-
29
Preface XML is a standardized markup language that defines a set of rules for encoding hierarchically structured documents in a human-readable text-based format. XML is in widespread...
-
10
Parsing XML in JavaScript? Monday, January 9, 2006 I have been doing some work with JavaScript / Ajax lately, and found myself needing to parse some XML (something I do quite often when building apps). However, I have n...
-
7
Parsing XML with Python Minidom November 29, 2019 By Rowell Leave a Comment A core skill...
-
7
Souce Code Run code on Go Playground parse-6.go |
-
9
[Golang] XML Parsing Example (4) February 24, 2015 In this exmaple, we will parse a
-
10
[Golang] XML Parsing Example (6) - Parse OPML Concisely February 26, 2015 The previo...
-
3
[Golang] XML Parsing Example (5)Based on previous examples, this post shows how to parse OPML file. The following OPML example comes from my web f...
-
9
Souce Code Run code on Go Playground parse-7.go |
-
11
[Golang] XML Parsing Example (2) Updated: February 21, 2015 following previous p...
-
6
[Golang] XML Parsing Example (1) Updated: February 21, 2015 Assume we have a XML file as follows:
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK