Skip to content

Instantly share code, notes, and snippets.

@un1t
Last active January 3, 2022 09:36
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save un1t/68f79d68be50489c0d39 to your computer and use it in GitHub Desktop.
Save un1t/68f79d68be50489c0d39 to your computer and use it in GitHub Desktop.
Golang XML stream parser
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)
}
@giriannamalai
Copy link

if inElement == "offer" {

}

What If I have a sub element "today" under "offer", how do I loop through it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment