1

I want to read an XML file from an URL and I want to parse it. How can I do this in Java??

1

5 Answers 5

3

Reading from a URL is know different than any other input source. There are several different Java tools for XML parsing.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.can you list some of them?
Here is a good list: java-source.net/open-source/xml-parsers. I have had good success with Xerces, but I really tried out many.
2

You can use Xstream it supports this.

URL url = new URL("yoururl");
BufferedReader in = new BufferedReader(
                new InputStreamReader(
                url.openStream()));



xSteamObj.fromXML(in);//return parsed object

3 Comments

All XML binding/serialization libraries support this use case. Check out: bdoughan.blogspot.com/2010/10/…
@Blaise thanks , @Srivigneshwar Check link given by Blaise it is helpful.
What is xSteamObj?
1

Two steps:

  1. Get the bytes from the server.
  2. Create a suitable XML source for it, perhaps even a Transformer.

Connect the two and get e.g. a DOM for further processing.

Comments

1

I use JDOM:

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.*;

StringBuilder responseBuilder = new StringBuilder();
try {
 // Create a URLConnection object for a URL
 URL url = new URL( "http://127.0.0.1" );
 URLConnection conn = url.openConnection();
 HttpURLConnection httpConn;

 httpConn = (HttpURLConnection)conn;
 BufferedReader rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
 String line;

 while ((line = rd.readLine()) != null)
 {
  responseBuilder.append(line + '\n');
 }
}
catch(Exception e){
 System.out.println(e);
}

SAXBuilder sb = new SAXBuilder();
Document d = null;
try{
    d = sb.build( new StringReader( responseBuilder.toString() ) );
}catch(Exception e){
    System.out.println(e);
}

Of course, you can cut out the whole read URL to string, then put a string reader on the string, but Ive cut/pasted from two different areas. So this was easier.

Comments

0

This is a good candidate for using Streaming parser : StAX StAX was designed to deal with XML streams serially; than compared to DOM APIs that needs entire document model at one shot. StAX also assumes that the contents are dynamic and the nature of XML is not really known. StAX use cases comprise of processing pipeline as well.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.