I want to read a xml code from an url and print it, using java. The URL is http://ste.hwg.cz/values.xml
I tried many codes after reading stackoverflow answers but it doesnt work.
By the way , Im new to Java, I just programmed Pascal and Delphi
I want to read a xml code from an url and print it, using java. The URL is http://ste.hwg.cz/values.xml
I tried many codes after reading stackoverflow answers but it doesnt work.
By the way , Im new to Java, I just programmed Pascal and Delphi
This is based on my tiny research on SO.
For xml parsing of an inputstream you can do:
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
If you want to print XML directly onto the screen you can use TransformerFactory
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
TransformerFactory factory = TransformerFactory.newInstance();
Transformer xform = factory.newTransformer();
// that’s the default xform; use a stylesheet to get a real one
xform.transform(new DOMSource(doc), new StreamResult(System.out));
Here's the code I use for this kind of tasks:
public void readFromUrl(String inurl){
try {
URL url = new URL(inurl);
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// HERE YOU CAN PRINT/LOG/SAVE THE LINE.
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
P.S.
You can use StringBuilder to build a String containing your XML.