MikeB
MikeB

Reputation: 37

Java IO cannot find existing file from URL

I have a weird problem, i have to parse XML file to get data, when I parse file: http://www.nbp.pl/kursy/xml/c073z070413.xml, all works ok (file is parsed), but when I try parse file : http://www.nbp.pl/kursy/xml/a002z020103.xml then I get a message that program cant find this file (In browser, the XML file works)

Exception:

java.io.FileNotFoundException: C:\Projects\AreYouSmart\abch.dtd (Could not found file)

Below is a full example code. (Code is taken from StackOverflow: XML parse file from HTTP)

public class TylkoPobieranie {

    public static void main(String[] args) {
        try {
            new TylkoPobieranie().start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void start() throws Exception {
        // link work: URL url = new URL("http://www.nbp.pl/kursy/xml/c073z070413.xml");
        URL url = new URL("http://www.nbp.pl/kursy/xml/a002z020103.xml");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("pozycja");

        for (int i = 0; i < descNodes.getLength(); i++) {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }

    private Document parseXML(InputStream stream) throws Exception {
        DocumentBuilderFactory objDocumentBuilderFactory = null;
        DocumentBuilder objDocumentBuilder = null;
        Document doc = null;
        try {
            objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            //ANSWER:
             objDocumentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

            objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();

            doc = objDocumentBuilder.parse(stream);
        } catch (Exception ex) {
            throw ex;
        }

        return doc;
    }
}

Upvotes: 2

Views: 588

Answers (2)

stepanian
stepanian

Reputation: 11433

That XML file has the line:

<!DOCTYPE tabela_kursow SYSTEM "abch.dtd">

It is the abch.dtd file that it cannot find.

Try this:

objDocumentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

Upvotes: 1

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

By default, Xerces (the built-in XML parser in Java) will try to load an external DTD file even if the parser is non-validating.

Calling setValidating(false) has no effect since it is already non-validating by default to start with. You can turn off external DTD loading after constructing the factory:

objDocumentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", 
                                     false);

Upvotes: 1

Related Questions