Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: encoding/xml: Indent function #58994

Closed
ghost opened this issue Mar 12, 2023 · 1 comment
Closed

proposal: encoding/xml: Indent function #58994

ghost opened this issue Mar 12, 2023 · 1 comment

Comments

@ghost
Copy link

ghost commented Mar 12, 2023

If I want to indent some JSON bytes, I can use the helpful json.Indent:

https://godocs.io/encoding/json#Indent

However XML does not have a similar function, so you are forced to do a roundtrip:

package indent

import "encoding/xml"

func indent_XML(src []byte) ([]byte, error) {
   type node struct {
      Children []node `xml:",any"`
      Text     string `xml:",chardata"`
      XMLName  xml.Name
   }
   var dst node
   err := xml.Unmarshal(src, &dst)
   if err != nil {
      return nil, err
   }
   return xml.MarshalIndent(dst, "", " ")
}

and even then, it seems the result is not valid:

<regionalRating>
 <rating>TV-PG</rating>
 <region>CA</region>&#xA;      &#xA;      &#xA;
</regionalRating>

I think it would be helpful if an xml.Indent was available.

@ghost ghost added the Proposal label Mar 12, 2023
@ghost
Copy link
Author

ghost commented Mar 13, 2023

here is an implementation that might work:

package xml

import (
   "bytes"
   "encoding/xml"
   "io"
)

func Indent(dst io.Writer, src io.Reader, prefix, indent string) error {
   decode := xml.NewDecoder(src)
   encode := xml.NewEncoder(dst)
   encode.Indent(prefix, indent)
   for {
      token, err := decode.Token()
      if err == io.EOF {
         return encode.Flush()
      }
      if err != nil {
         return err
      }
      data, ok := token.(xml.CharData)
      if ok {
         token = xml.CharData(bytes.TrimSpace(data))
      }
      if err := encode.EncodeToken(token); err != nil {
         return err
      }
   }
}

@seankhliao seankhliao changed the title encoding/xml: Indent function proposal: encoding/xml: Indent function Mar 13, 2023
@gopherbot gopherbot added this to the Proposal milestone Mar 13, 2023
@ianlancetaylor ianlancetaylor moved this to Incoming in Proposals Mar 15, 2023
@ghost ghost closed this as completed May 9, 2023
@golang golang locked and limited conversation to collaborators May 8, 2024
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant