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

xmlvalid validates with libxml2, which reports it as Premature end of data in tag. It checks the whole document in your browser and lists every schema error with its line and column, not only the first.

Premature end of data in tag note line 1

Example

Reports the error
<note>
  <to>Ana</to>
Fixed
<note>
  <to>Ana</to>
</note>