ria
ria

Reputation: 7974

SAXParseException when URL is non-existent

I am trying to parse an xml using DocumentBuilder's parse method which takes URI as an argument. For this I create a String object representing the URI and then call the parse method passing the String object as the argument.

The parse method call works fine, returns a new DOM object. However, when I try to print the returned DOM object, it says:

org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed. The code snippet for parsing the xml is as shown below:

String sURL="http://host:port/myapp/myfile.xml";   
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();      
doc = dBuilder.parse(sURL);

However, when the URL is a non-existent one, the parse method still returns

org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.

The xml is a normal xml, something as shown below:

    <?xml version="1.0" encoding="utf-8"?>
<Data>
    <ColorMessages>
        <Message Color="RED">Warning: The batch color level is red. Please check it out!</Message>
        <Message Color="YELLOW">Alert: This batch color level is yellow. Please stay on alert!</Message>
        <Message Color="GREEN">Cool: The batch color level is green. Nice!</Message>
        <Message Color="BLUE">Excellent: The batch color level is blue. Great job!</Message>
    </ColorMessages>
</Data>

Any thoughts on how I could identify a non-existent URL during a parse method call?

Thanks.

Upvotes: 0

Views: 201

Answers (1)

BillRobertson42
BillRobertson42

Reputation: 12883

Personally I prefer to set up the network connection, or open the file myself and just pass the stream to the xml sub-system. Its a bit more work, but you can control what his going on. i.e. you're not dependent upon what somebody else thought was a good idea in that situation.

When you do this, you also need to make sure you close the streams. The XML bits underneath don't make the assumption that that is what you want.

Upvotes: 2

Related Questions