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.
Run code on Go Playground
parse-3.go |
repository |
view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 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: