Essential Go XML  Edit on GitHub      File Issue

Parse XML from file

We can decode XML data from a file on disk.

func decodeFromReader(r io.Reader) (*People, error) {
	var people People
	decoder := xml.NewDecoder(r)
	err := decoder.Decode(&people)
	if err != nil {
		return nil, err
	}
	return &people, nil
}

func decodeFromString(s string) (*People, error) {
	r := bytes.NewBufferString(s)
	return decodeFromReader(r)
}

func decodeFromFile(path string) (*People, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return decodeFromReader(f)
}
&main.People{Person:[]main.Person{main.Person{Age:34, FirstName:"John", Address:main.Address{City:(*string)(0xc42000e3f0), State:"CA"}}, main.Person{Age:23, FirstName:"Julia", Address:main.Address{City:(*string)(nil), State:""}}}}

By writing a helper function decodeFromReader, we can easily write wrappers that will work on files, strings or network connections.

  ↑ ↓ to navigate     ↵ to select     Esc to close