tags:

views:

88

answers:

2

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.

+1  A: 

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.

David Dorward
Whoops, mistyped that fragment, forgot the surrounding tag.
Presumably it is then still an attempt to manually recreate the actual data and not the data that is actually causing the problem?…
David Dorward
Correct.The actual data has some more information and a messageBut I don't think that a question mark or @ sign could cause this.
+1  A: 

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.

Riduidel