Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Can Document Builder parse an XML file from a URL?

843834Sep 3 2009 — edited Sep 3 2009
Warning: Java newbie here...

My problem is that I am able to parse an XML file if it is copied into my project, but not if it is a full URL. Here is what I got so far, that works.
import java.io.*;
import java.net.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

try {
    File file = new File("path/to/file.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    NodeList nodeLst = doc.getElementsByTagName("Names");
    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node parentNode = nodeLst.item(s);
        if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
            Element parentElmnt = (Element) parentNode;
            NodeList nameElmntLst = parentElmnt.getElementsByTagName("Name");
            //etc.
        }
    }
} catch (Exception e){
    e.printStackTrace();
}
So building off of this I have tried to parse an input stream like this:
URL url = new URL("http://example.com/file.xml");
InputStream is = url.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
which gives me the following error
[Fatal Error] :-1:-1: Premature end of file.
LOG: HME receiver connected
org.xml.sax.SAXParseException: Premature end of file.

I also even tried to write the file locally like this:
URL url = new URL("http://example.com/file.xml");
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.connect();
InputStream is = urlcon.getInputStream();
File file = new File("path/to/file.xml");
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while((len=is.read(buf))>0)
    out.write(buf,0,len);
out.close();
is.close();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
This gives the same error.

If anyone can point me in the right direction I would forever thankful. I've tried search Google and the Sun forums, but haven't quite found the solution. I think it is because I need to try something else completely. Thank you for reading.

~~~~ Jeremy
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 1 2009
Added on Sep 3 2009
7 comments
718 views