I needed this a while back, for both JSON and XML.

JSON was the easy part =)

Here's my repo for an XML prettifier https://github.com/juztin/xmlfmt


*  (ignore the install directions in my readme, the domain is wrong)*You 
can install it via:
go get install https://github.com/juztin/xmlfmt
Then just pass it whatever XML:

curl -s http://www.w3schools.com/xml/note.xml | xmlfmt
echo "<xml><test>blah</test></xml>" | xmlfmt


Or... Here's the actual code:
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))
}

Hope that helps =)



On Friday, November 4, 2016 at 3:32:24 PM UTC-6, Tong Sun wrote:
>
> How to beautify a given XML string in GO? 
>
> The xml.MarshalIndent() only apply to a GO structure, not XML strings. 
>
> Thanks
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to