# XML document structures must start and end within the same entity

Source: https://xmlvalid.com/errors/xml-document-structures-must-start-and-end-within-the-same-entity

> The document ends while an element, comment or CDATA section is still open.

The message, as Java reports it: `XML document structures must start and end within the same entity.`

## Why it happens

- A truncated file or stream: an interrupted download, a buffer that was not flushed, a stream closed too early.
- A missing end tag for the root element.
- An unclosed comment (`\<!--` without `-->`) or CDATA section that swallowed the rest of the file.

## How to fix it

- Check that the file is complete: compare its size with the source, and when you write XML yourself, close or flush the writer before reading it back. Then look for the element or comment that is never closed.
- Java's schema validation (`javax.xml.validation.Validator`, and JAXB or Spring on top of it) throws at the first error unless you set an `ErrorHandler` whose `error()` records the `SAXParseException` and carries on; each one has `getLineNumber()` and `getColumnNumber()`. A well-formedness error ends parsing whatever the handler does.

## The same problem in xmlvalid

libxml2, which xmlvalid validates with, reports it as [Premature end of data in tag](https://xmlvalid.com/errors/premature-end-of-data): `Premature end of data in tag note line 1`

## Example that fails

```xml
<note>
  <to>Ana</to>
```

## Fixed

```xml
<note>
  <to>Ana</to>
</note>
```
