Fix exception on stream close

As discussed in closed issue #77.

Now with added bonus: don't search for an xml declaration twice!