Last active
August 29, 2015 14:04
-
-
Save tkrajina/9cc8fb366d0c48f7eade to your computer and use it in GitHub Desktop.
Traversing XML in GO
This file contains 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 | |
import ( | |
"encoding/xml" | |
"fmt" | |
"os" | |
) | |
func main() { | |
f, _ := os.Open("test_files/gpx1.1_with_all_fields.gpx") | |
decoder := xml.NewDecoder(f) | |
var err error | |
var token xml.Token | |
xmlPath := make([]string, 0, 20) | |
for token, err = decoder.Token(); token != nil && err == nil; token, err = decoder.Token() { | |
fmt.Println("Path:", xmlPath) | |
switch typedToken := token.(type) { | |
case xml.StartElement: | |
xmlPath = append(xmlPath, typedToken.Name.Local) | |
fmt.Println("StartElement:", typedToken.Name.Local) | |
for i := 0; i < len(typedToken.Attr); i++ { | |
fmt.Println(" attr:", typedToken.Attr[i].Name, "->", typedToken.Attr[i].Value) | |
} | |
case xml.EndElement: | |
xmlPath = xmlPath[0:len(xmlPath) - 1] | |
fmt.Println("EndElement:", typedToken.Name.Local) | |
case xml.CharData: | |
fmt.Println("CharData:", string([]byte(typedToken))) | |
case xml.Comment: | |
fmt.Println("Comment:", string([]byte(typedToken))) | |
case xml.ProcInst: | |
fmt.Println("ProcInst:", string(typedToken.Inst)) | |
case xml.Directive: | |
fmt.Println("Directive:", typedToken) | |
default: | |
fmt.Println("Something else") | |
} | |
} | |
fmt.Println("Err:", err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment