gadzik gadzik - 3 months ago 27
Java Question

parsing XML from URL in java

Hello i have a big problem . i have to parse XML file from URL/HTTP and work on it in java , but i get exception always when i do it . address is ok because it is www of a bank . please help me

import java.net.URL;

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

import org.w3c.dom.Document;

public class MainClass {
public static void main(String [] args){
String url = "http://api.nbp.pl/api/exchangerates/rates/c/gbp/2015-01-01/2015-01-31";
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

doc.getDocumentElement().normalize();
System.out.println ("Root element: " +
doc.getDocumentElement().getNodeName());

}
catch (Exception e)
{
e.printStackTrace();
}
}
}


error :

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at pl.parser.nbp.MainClass.main(MainClass.java:17)

and second case :

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;
public class MainClass {
public static void main(String [] args){
String url = "http://api.nbp.pl/api/exchangerates/rates/a/gbp/2012-01-01/2012-01-31/";
try
{
DocumentBuilderFactory f =
DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(url);

doc.getDocumentElement().normalize();
System.out.println ("Root element: " +
doc.getDocumentElement().getNodeName());

}
catch (Exception e)
{
e.printStackTrace();
}
}
}


error :
[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; systemId: http://api.nbp.pl/api/exchangerates/rates/a/gbp/2012-01-01/2012-01-31/; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at pl.parser.nbp.MainClass.main(MainClass.java:19)

Answer

By default, the URL returns data in JSON format. You see an XML in the browser because the way the browser negotiates a return type (via Accept header).

You can either parse the data as JSON, or change the URL to http://api.nbp.pl/api/exchangerates/rates/c/gbp/2015-01-01/2015-01-31?format=xml.

Notice ?format=xml at the end.

See the User manual.

Comments