Read a file into a []byte for new XML unmarshal

1,084 views
Skip to first unread message

Mitchell Hashimoto

unread,
Jan 24, 2012, 5:43:33 PM1/24/12
to golan...@googlegroups.com
I've recently updated to the latest weekly release since we needed some of the new libraries, and I'm just going through some external dependencies and updating code to be able to compile. The final error I'm at is the following:

cannot convert fd (type *os.File) to type []byte

This is happening with the new xml.Unmarshal method since it was changed from an io.Reader to a []byte argument. I realize I can do a bufio read loop over the Reader to get a []byte, manually appending data. Is there a shorter method of taking an io.Reader and reading all of the contents into a []byte?

Kyle Lemons

unread,
Jan 24, 2012, 5:47:28 PM1/24/12
to golan...@googlegroups.com
At the weekly I think it's still a []byte (I only mention this in case you're at tip by accident, though I could be wrong).  At tip, you can use the Decoder interface.


The change was made to bring its API into line with gob and JSON.

Mitchell Hashimoto

unread,
Jan 24, 2012, 5:54:13 PM1/24/12
to Kyle Lemons, golan...@googlegroups.com
On Tue, Jan 24, 2012 at 2:47 PM, Kyle Lemons <kev...@google.com> wrote:
At the weekly I think it's still a []byte (I only mention this in case you're at tip by accident, though I could be wrong).  At tip, you can use the Decoder interface.


The change was made to bring its API into line with gob and JSON.


Got it! Thanks, that worked great.

Gustavo Niemeyer

unread,
Jan 24, 2012, 5:55:58 PM1/24/12
to golan...@googlegroups.com
> This is happening with the new xml.Unmarshal method since it was changed
> from an io.Reader to a []byte argument. I realize I can do a bufio read loop
> over the Reader to get a []byte, manually appending data. Is there a shorter
> method of taking an io.Reader and reading all of the contents into a []byte?

Just convert your old

err := xml.Unmarshal(a, b)

onto:

err := xml.NewDecoder(a).Decode(b)

The reason it doesn't do it automatically for you with gofix is that
the new xml.Unmarshal has a similar signature to the old one, so it's
not entirely easy to figure if it should be updated or not. That said,
it should be doable for some simpler cases, and I may improve the
gofix module a bit more if I find the time.

--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/plus
http://niemeyer.net/twitter
http://niemeyer.net/blog

-- I'm not absolutely sure of anything.

Reply all
Reply to author
Forward
0 new messages