开发者

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

开发者 https://www.devze.com 2022-12-23 12:22 出处:网络
I have a service that gives some car information in an xml format. <?xml version=\"1.0\" encoding=\'UTF-8\'?>

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>
      <nam开发者_C百科e>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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消