]> Cypherpunks repositories - gostls13.git/commitdiff
xml: omit newline at beginning of MarshalIndent output
authorShivakumar GN <shivakumar.gn@gmail.com>
Sun, 3 Feb 2013 16:21:07 +0000 (11:21 -0500)
committerRuss Cox <rsc@golang.org>
Sun, 3 Feb 2013 16:21:07 +0000 (11:21 -0500)
(Still valid XML.)

Fixes #3354.

R=golang-dev, dave
CC=golang-dev
https://golang.org/cl/7288047

src/pkg/encoding/xml/marshal.go
src/pkg/encoding/xml/marshal_test.go

index 803805fed30f3474723ef76a10d7fd200c936180..ea891bfb3ee5ba13cbb6d3a81d0d265e47eb345e 100644 (file)
@@ -124,6 +124,7 @@ type printer struct {
        prefix     string
        depth      int
        indentedIn bool
+       putNewline bool
 }
 
 // marshalValue writes one or more XML elements representing val.
@@ -394,7 +395,11 @@ func (p *printer) writeIndent(depthDelta int) {
                }
                p.indentedIn = false
        }
-       p.WriteByte('\n')
+       if p.putNewline {
+               p.WriteByte('\n')
+       } else {
+               p.putNewline = true
+       }
        if len(p.prefix) > 0 {
                p.WriteString(p.prefix)
        }
index 67fcfd9ed565b6534247ae191565045bc2fb7473..ed856813a7eb92dd161a60f3142036a69ff29f48 100644 (file)
@@ -7,6 +7,7 @@ package xml
 import (
        "bytes"
        "errors"
+       "fmt"
        "io"
        "reflect"
        "strconv"
@@ -840,6 +841,24 @@ var marshalErrorTests = []struct {
        },
 }
 
+var marshalIndentTests = []struct {
+       Value     interface{}
+       Prefix    string
+       Indent    string
+       ExpectXML string
+}{
+       {
+               Value: &SecretAgent{
+                       Handle:    "007",
+                       Identity:  "James Bond",
+                       Obfuscate: "<redacted/>",
+               },
+               Prefix:    "",
+               Indent:    "\t",
+               ExpectXML: fmt.Sprintf("<agent handle=\"007\">\n\t<Identity>James Bond</Identity><redacted/>\n</agent>"),
+       },
+}
+
 func TestMarshalErrors(t *testing.T) {
        for idx, test := range marshalErrorTests {
                _, err := Marshal(test.Value)
@@ -884,6 +903,19 @@ func TestUnmarshal(t *testing.T) {
        }
 }
 
+func TestMarshalIndent(t *testing.T) {
+       for i, test := range marshalIndentTests {
+               data, err := MarshalIndent(test.Value, test.Prefix, test.Indent)
+               if err != nil {
+                       t.Errorf("#%d: Error: %s", i, err)
+                       continue
+               }
+               if got, want := string(data), test.ExpectXML; got != want {
+                       t.Errorf("#%d: MarshalIndent:\nGot:%s\nWant:\n%s", i, got, want)
+               }
+       }
+}
+
 type limitedBytesWriter struct {
        w      io.Writer
        remain int // until writes fail