I've been playing around with an XML token stream processing API:
https://godoc.org/mellium.im/xmlstream
It's still experimental, and likely to change, but it would probably
be pretty easy to write a transformer that keeps track of iindentation
and adds/removes whitespace tokens as necessary (in fact, that's one
of the things I wanted something like this for in the first place).
I should also state that in this example you could of course just use
MarshalIndent, the point was to show that you could do it manually if
you need more customized formatting.
How to beautify a given XML string in GO?
The xml.MarshalIndent() only apply to a GO structure, not XML strings.
curl -s http://www.w3schools.com/xml/note.xml | xmlfmt
echo "<xml><test>blah</test></xml>" | xmlfmt
package main
import (
"bufio"
"encoding/xml"
"fmt"
"os"
)
type node struct {
Attr []xml.Attr
XMLName xml.Name
Children []node `xml:",any"`
Text string `xml:",chardata"`
}
/* Usage:
* % echo "<xml><test>blah</test></xml>" | go run xmlfmt.go
*/
func main() {
reader := bufio.NewReader(os.Stdin)
decoder := xml.NewDecoder(reader)
n := node{}
if err := decoder.Decode(&n); err != nil {
fmt.Println(err)
os.Exit(1)
}
b, err := xml.MarshalIndent(n, "", " ")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(string(b))
}