Last active
January 3, 2022 09:36
-
-
Save un1t/68f79d68be50489c0d39 to your computer and use it in GitHub Desktop.
Golang XML stream parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// https://github.com/dps/go-xml-parse/blob/master/go-xml-parse.go | |
import ( | |
"fmt" | |
"os" | |
"encoding/xml" | |
) | |
type Offer struct { | |
Name string `xml:"name"` | |
Url string `xml:"url"` | |
Price string `xml:"price"` | |
Category string `xml:"categoryId"` | |
Picture string `xml:"picture"` | |
Author string `xml:"author"` | |
publisher string `xml:"publisher"` | |
series string `xml:"series"` | |
year string `xml:"year"` | |
ISBN string `xml:"ISBN"` | |
binding string `xml:"binding"` | |
page_extent string `xml:"page_extent"` | |
downloadable string `xml:"downloadable"` | |
} | |
func main() { | |
xmlFile, err := os.Open("2.xml") | |
if err != nil { | |
fmt.Println("Error opening file:", err) | |
return | |
} | |
defer xmlFile.Close() | |
decoder := xml.NewDecoder(xmlFile) | |
total := 0 | |
var inElement string | |
for { | |
// Read tokens from the XML document in a stream. | |
t, _ := decoder.Token() | |
if t == nil { | |
break | |
} | |
// Inspect the type of the token just read. | |
switch se := t.(type) { | |
case xml.StartElement: | |
// If we just read a StartElement token | |
inElement = se.Name.Local | |
// ...and its name is "page" | |
if inElement == "offer" { | |
var offer Offer | |
// decode a whole chunk of following XML into the | |
// variable p which is a Page (se above) | |
decoder.DecodeElement(&offer, &se) | |
// fmt.Println(offer.Url) | |
// Do some stuff with the page. | |
total++ | |
} | |
default: | |
} | |
} | |
fmt.Printf("Total: %d \n", total) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if inElement == "offer" {
}
What If I have a sub element "today" under "offer", how do I loop through it?