I want to read an XML file from an URL and I want to parse it. How can I do this in Java??
Asked
Active
Viewed 2.2k times
1
-
possible duplicate of [Best XML parser for Java](http://stackoverflow.com/questions/373833/best-xml-parser-for-java) – Joel Jan 11 '11 at 19:37
5 Answers
3
Reading from a URL is know different than any other input source. There are several different Java tools for XML parsing.

jzd
- 23,473
- 9
- 54
- 76
-
-
1Here is a good list: http://java-source.net/open-source/xml-parsers. I have had good success with Xerces, but I really tried out many. – jzd Jan 11 '11 at 19:42
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

jmj
- 237,923
- 42
- 401
- 438
-
1All XML binding/serialization libraries support this use case. Check out: http://bdoughan.blogspot.com/2010/10/how-does-jaxb-compare-to-xstream.html – bdoughan Jan 11 '11 at 20:12
-
-
1
Two steps:
- Get the bytes from the server.
- Create a suitable XML source for it, perhaps even a Transformer.
Connect the two and get e.g. a DOM for further processing.

Thorbjørn Ravn Andersen
- 73,784
- 33
- 194
- 347
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.

Zak
- 24,947
- 11
- 38
- 68
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.

ring bearer
- 20,383
- 7
- 59
- 72