Skip to content

Instantly share code, notes, and snippets.

@adamluzsi
Created September 6, 2018 07:48
Show Gist options
  • Save adamluzsi/55d6dff9ed83c1b183c5b410f13e69ec to your computer and use it in GitHub Desktop.
Save adamluzsi/55d6dff9ed83c1b183c5b410f13e69ec to your computer and use it in GitHub Desktop.
go xml fmt based on Sam Whited code
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"log"
"strings"
)
const flatxml = `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://example.com/ns"><soapenv:Header/><soapenv:Body><ns:request><ns:customer><ns:id>123</ns:id><ns:name type="NCHZ">John Brown</ns:name></ns:customer></ns:request></soapenv:Body></soapenv:Envelope>`
func main() {
buf := new(bytes.Buffer)
d := xml.NewDecoder(strings.NewReader(flatxml))
e := xml.NewEncoder(buf)
e.Indent("", " ")
tokenize:
for {
tok, err := d.Token()
switch {
case err == io.EOF:
e.Flush()
break tokenize
case err != nil:
log.Fatal(err)
}
e.EncodeToken(tok)
}
newxml := buf.String()
fmt.Println(newxml)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment