private function append(\Closure $appendTo, string $type): XmlStreamWriter
    {
        libxml_use_internal_errors(true);
        try {
            $appendTo(end($this->openElements));
        } catch (\DOMException $e) {
            throw new XmlException('Error writing "' . $type, $e);
        }

        $errors = libxml_get_errors();
        if (!empty($errors)) {
            libxml_clear_errors();
            throw new XmlException(
                    'Error writing "' . $type . '": '
                    . implode(', ', array_map(
                            function($error) { return trim($error->message); },
                            $errors
                    ))
            );
        }

        return $this;
    }