6

[Golang] XML Parsing Example (4)

 2 years ago
source link: http://siongui.github.io/2015/02/24/go-parse-xml-example-4/
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.
neoserver,ios ssh client

[Golang] XML Parsing Example (4)

February 24, 2015

In this exmaple, we will parse a div element with multiple span child elements:

example-4.xml | repository | view raw

<?xml version="1.0" encoding="UTF-8"?>
<div>
  <span>SpanText1</span>
  <span>SpanText2</span>
  <span>SpanText3</span>
</div>

To parse multiple span child elements, the struct field in div struct of previous example [3]:

ChildSpan   span

becomes:

SpanList    []span          `xml:"span"`

The type span becomes []span, and `xml:"span` is added to indicate the tag name of child elements.

Run code on Go Playground

parse-4.go | repository | view raw

package main

import (
	"io/ioutil"
	"encoding/xml"
	"fmt"
)

type div struct {
	XMLName		xml.Name	`xml:"div"`
	SpanList	[]span		`xml:"span"`
}

type span struct {
//	XMLName		xml.Name	`xml:"span"`
	Text		string		`xml:",chardata"`
}

func main() {
	d := div{}
	xmlContent, _ := ioutil.ReadFile("example-4.xml")
	err := xml.Unmarshal(xmlContent, &d)
	if err != nil { panic(err) }
	fmt.Println(d)
	// uncomment XMLName struct field in span struct
	// the output of fmt.Println(d) will be:
	// {{ div} [{{ span} SpanText1} {{ span} SpanText2} {{ span} SpanText3}]}
}

The output result:

{{ div} [{SpanText1} {SpanText2} {SpanText3}]}

If you uncomment the following line:

//  XMLName         xml.Name        `xml:"span"`

The output will be:

{{ div} [{{ span} SpanText1} {{ span} SpanText2} {{ span} SpanText3}]}

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)

[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


[a]XML to Go struct : golang


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK