14

I have an XML file located at a location such as

http://example.com/test.xml

I'm trying to parse the XML file to use it in my program with xPath like this but it is not working.

Document doc = builder.parse(new File(url));

How can I get the XML file?

1
  • 1
    Why put a bounty of +100 for that ? See Nils response you just have to first get your xml file as a stream and then parse it. Commented May 12, 2011 at 9:10

6 Answers 6

21
+100

Try using URLConnection.getInputStream() for getting the handle of XML file.

See the below code, in that I am trying to open an xml file and printing all the description fields:

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

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

    private void start() throws Exception
    {
        URL url = new URL("http://localhost:8080/AutoLogin/resource/web.xml");
        URLConnection connection = url.openConnection();

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

        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();
            objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();

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

        return doc;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Here is the simple example for getting data form this string "http://www.gettingagile.com/feed/rss2/"

public class MainClassXml {

    public static void main(String args[]) throws URISyntaxException,
            ClientProtocolException, IOException, MalformedURLException {

        String url = "http://www.gettingagile.com/feed/rss2/";
        System.out.println("Url is careated****");
        URL url2 = new URL(url);
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        System.out.println("Entity is*****" + entity);
        try {
            String xmlParseString = EntityUtils.toString(entity);
            System.out.println("This Stirng to be Pasrse***" + xmlParseString);

            HttpURLConnection connection = (HttpURLConnection) url2
                    .openConnection();
            InputStream inputStream = connection.getInputStream();

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = builderFactory
                    .newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);
            document.getDocumentElement().normalize();

            System.out.println("Attributes are***" + document.getAttributes());

            NodeList nodeList = document.getElementsByTagName("rss");
            System.out.println("This is firstnode" + nodeList);
            for (int getChild = 0; getChild < nodeList.getLength(); getChild++) {

                Node Listnode = nodeList.item(getChild);
                System.out.println("Into the for loop"
                        + Listnode.getAttributes().getLength());
                Element firstnoderss = (Element) Listnode;
                System.out.println("ListNodes" + Listnode.getAttributes());
                System.out.println("This is node list length"
                        + nodeList.getLength());

                Node Subnode = nodeList.item(getChild);
                System.out.println("This is list node" + Subnode);
                System.out.println("rss attributes***************");
            }

        } catch (Exception exception) {

            System.out.println("Exception is" + exception);

        }
    }

Comments

1

Get rid of the new File():

Document doc = builder.parse(url);

Comments

1

A little more detail, based on laz answer:

String urlString = "http://example.com/test.xml";
URL url = new URL(urlString);
Document doc = builder.parse(url);

4 Comments

builder.parse cannot handle a URL.
Uhmm, ok, i made a mistake. But that's the way you should do it. First open a connection with a URL, read the content and then parse it. Sorry for that brother.
My answer is from 2010, you're referencing Java 8 that was released last year.
0

It's much easier with a XMLPullParser ... you don't have to deal with this event stuff and can quickly pick up some keywords ... I'm using it too ... only a couple of code lines :)

http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

Regarding HTTP and files have a look here Download a file with DefaultHTTPClient and preemptive authentication

1 Comment

Isn't it something for Android devices ?
-1
File fileXml = new File(url);

DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(fileXml);

it should go

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.