Skip to content

Instantly share code, notes, and snippets.

@nakagami
Created January 18, 2014 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakagami/8491586 to your computer and use it in GitHub Desktop.
Save nakagami/8491586 to your computer and use it in GitHub Desktop.
/*
sample.xml should be located in the default working directory
<foo>
<bar key="Key1" value="Value1" />
<bar key="Key2" value="Value2" />
</foo>
*/
package main
import (
"encoding/xml"
"fmt"
"io"
"os"
"bytes"
"path/filepath"
)
func main() {
var file *os.File
defer func() {
if file != nil {
file.Close()
}
}()
strapsFilePath, err := filepath.Abs("sample.xml")
if err != nil {
panic(err.Error())
}
// Open the straps.xml file
file, err = os.Open(strapsFilePath)
if err != nil {
panic(err.Error())
}
d := xml.NewDecoder(file)
for {
token, err := d.Token()
if err == io.EOF {
err = nil
break
}
if err != nil {
panic(err)
}
switch token.(type) {
case xml.StartElement:
se := token.(xml.StartElement)
fmt.Printf("StartElement:\n")
fmt.Printf("\tName.Space:%s\n", se.Name.Space)
fmt.Printf("\tName.Local:%s\n", se.Name.Local)
for _, attr := range se.Attr {
if attr.Name.Space == "" {
fmt.Printf("\t\t%s=%s\n", attr.Name.Local, attr.Value)
} else {
fmt.Printf("\t\t%s:%s=%s\n", attr.Name.Space, attr.Name.Lo
cal, attr.Value)
}
}
case xml.EndElement:
ee := token.(xml.EndElement)
fmt.Printf("EndElement:\n")
fmt.Printf("\tName.Space:%s\n", ee.Name.Space)
fmt.Printf("\tName.Local:%s\n", ee.Name.Local)
case xml.CharData:
cd := token.(xml.CharData)
fmt.Printf("CharData:\n")
fmt.Printf("\t%v(%s)\n", token, bytes.NewBuffer(cd).String())
case xml.Comment:
fmt.Printf("Comment:%v\n", token)
case xml.ProcInst:
fmt.Printf("ProcInst:%v\n", token)
case xml.Directive:
fmt.Printf("Directive:%v\n", token)
default:
panic("unknown xml token.")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment