Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/srom/xmlstream
Lightweight XML scanner built on top of Go's encoding/xml.
https://github.com/srom/xmlstream
Last synced: about 2 months ago
JSON representation
Lightweight XML scanner built on top of Go's encoding/xml.
- Host: GitHub
- URL: https://github.com/srom/xmlstream
- Owner: srom
- License: mit
- Created: 2014-06-25T15:23:04.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2015-05-15T03:42:49.000Z (over 9 years ago)
- Last Synced: 2024-10-14T22:20:34.932Z (2 months ago)
- Language: Go
- Homepage: http://godoc.org/github.com/srom/xmlstream
- Size: 287 KB
- Stars: 4
- Watchers: 2
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## Overview
Lightweight XML scanner built on top of Go's [encoding/xml](http://golang.org/pkg/encoding/xml/#Unmarshal).
It keeps the flexibility of xml.Unmarshal while allowing the parsing of huge XML files.Documentation: http://godoc.org/github.com/srom/xmlstream
## Usage
Say you want to parse the following XML file:
```xml
Jon Arbuckle
[email protected]
[email protected]
Garfield
Red British ShorthairDr. Liz Wilson
[email protected]
[email protected]
```
Step 1 → Define your struct objects like you would usually do it to use [xml.Unmarshal](http://golang.org/pkg/encoding/xml/#Unmarshal).
```Go
type Person struct {
Name string `xml:"FullName"`
Emails []Email `xml:"Email"`
}
type Email struct {
Where string `xml:"where,attr"`
Addr string
}type Cat struct {
Name string `xml:"Nickname"`
Breed string
}
```Step 2 → Create a new xmlstream.Scanner and iterate through it:
```Go
scanner := xmlstream.NewScanner(os.Stdin, new(Person), new(Cat))personCounter := 0
catCounter := 0
for scanner.Scan() {
tag := scanner.Element()
switch el := tag.(type) {
case *Person:
person := *el
personCounter++
fmt.Printf("Human N°%d: %s, %s\n", personCounter, person.Name, person.Emails)case *Cat:
cat := *el
catCounter++
fmt.Printf("Cat N°%d: %s, %s\n", catCounter, cat.Name, cat.Breed)
}
}if err := scanner.Err(); err != nil {
t.Errorf("Error while scanning XML: %v\n", err)
}
```Output:
Human N°1: Jon Arbuckle, [{home [email protected]} {work [email protected]}]
Cat N°1: Garfield, Red British Shorthair
Human N°2: Dr. Liz Wilson, [{home [email protected]} {work [email protected]}]## About & License
Built by [Romain Strock](http://romainstrock.com) under the ☀ of London.
Released under [MIT License](https://github.com/srom/xmlstream/blob/master/LICENSE).