user211992
user211992

Reputation: 330

How to solve docbuilder SAX exception: unexpected end of document?

I have a service that gives some car information in an xml format.

<?xml version="1.0" encoding='UTF-8'?>
<cars>
   <car>
      <id>5</id>
      <name>qwer</name>
   </car>
   <car>
      <id>6</id>
      <name>qwert</name>
   </car>
</cars>

Now the problem that I'm having is that my

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xml);

Sometimes throws a SAXException (sometimes it works just fine, but when I reboot the server (still in development) I sometimes keep getting it) with as cause SAXException: unexpected end of document.

But when I place a bufferreader there to see what it's receiving and I copy the value into an xml document and I open it in firefox/ie it looks just fine.

Upvotes: 0

Views: 1717

Answers (2)

Riduidel
Riduidel

Reputation: 22308

You get this exception because the example you entered is a valid XML fragment (as a consequence readable by Firefox), but an invalid XML document, as it has more than one root node, which is forbidden by XML rules. Try to create one XML document for each <car> tag, and SAX will be fine.

Upvotes: 1

Quentin
Quentin

Reputation: 944321

An XML document must have one, and only one, root element.

You should have a <cars> element (or similar) wrapping your group of <car>s.

The error message doesn't make sense though - since you have unexpected content after what should be the end of the document.

Upvotes: 2

Related Questions