package main
import (
"encoding/xml"
//"fmt"
//"strings"
"io/ioutil"
"log"
)
type Result struct {
Person []Person
}
type Person struct {
Name string
Age int
Career string
Interests Interests
}
type Interests struct {
Interest []string
}
func main() {
content, err := ioutil.ReadFile("studygolang.xml")
if err != nil {
log.Fatal(err)
}
var result Result
err = xml.Unmarshal(content, &result)
if err != nil {
log.Fatal(err)
}
log.Println(result)
}
/*
func main() {
var t xml.Token
var err error
input := `<Person><FirstName>Xu</FirstName><LastName>Xinhua</LastName></Person>`
inputReader := strings.NewReader(input)
// 从文件读取,如可以如下:
// content, err := ioutil.ReadFile("studygolang.xml")
// decoder := xml.NewDecoder(bytes.NewBuffer(content))
decoder := xml.NewDecoder(inputReader)
for t, err = decoder.Token(); err == nil; t, err = decoder.Token() {
switch token := t.(type) {
case xml.StartElement:
name := token.Name.Local
fmt.Printf("Token name: %s\n", name)
for _, attr := range token.Attr {
attrName := attr.Name.Local
attrValue := attr.Value
fmt.Printf("An attribute is: %s %s\n", attrName, attrValue)
}
case xml.EndElement:
fmt.Printf("Token of '%s' end\n", token.Name.Local)
case xml.CharData:
content := string([]byte(token))
fmt.Printf("This is the content: %v\n", content)
default:
// ...
}
}
}
*/
网友评论