Fit fields of a webservice


My question is this: I need to access a server that provides me with the temperature of a place by indicating what that place is, from a Java application. For now that I get an http request request the problem is that they give me too much redundant information and I would like to know if there is any way to filter those fields received from the web service to stay alone with the ones I am interested in, which are tempMax and temMin. I leave here my code and the response I receive:


public class WeatherService extends HttpServlet {

    public static void main(String[] args) {
        // System.out.println("\nOutput: \n" + callURL(
        // ""));

                .println("\nOutput: \n"
                        + callURL(""));


    public static String callURL(String myURL) {
        System.out.println("Requeted URL:" + myURL);
        StringBuilder sb = new StringBuilder();
        URLConnection urlConn = null;
        InputStreamReader in = null;
        try {
            URL url = new URL(myURL);
            urlConn = url.openConnection();
            if (urlConn != null)
                urlConn.setReadTimeout(60 * 1000);
            if (urlConn != null && urlConn.getInputStream() != null) {
                in = new InputStreamReader(urlConn.getInputStream(),

                BufferedReader bufferedReader = new BufferedReader(in);
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = != -1) {
                        sb.append((char) cp);

        } catch (Exception e) {
            throw new RuntimeException("Exception while calling URL:" + myURL,
        return sb.toString();



Request URL: link


<weatherdata><location><name>Madrid</name><type></type><country>ES</country><timezone></timezone><location altitude="0" latitude="40.4165" longitude="-3.70256" geobase="geonames" geobaseid="3117735"></location></location><credit></credit><meta><lastupdate></lastupdate><calctime>0.0094</calctime><nextupdate></nextupdate></meta><sun rise="2016-05-26T04:49:22" set="2016-05-26T19:35:01"></sun><forecast><time day="2016-05-26"><symbol number="804" name="overcast clouds" var="04d"></symbol><precipitation></precipitation><windDirection deg="230" code="SW" name="Southwest"></windDirection><windSpeed mps="2.41" name="Light breeze"></windSpeed><temperature day="23.15" min="12.75" max="24.29" night="12.75" eve="23.4" morn="23.15"></temperature><pressure unit="hPa" value="952.66"></pressure><humidity value="50" unit="%"></humidity><clouds value="overcast clouds" all="88" unit="%"></clouds></time><time day="2016-05-27"><symbol number="800" name="clear sky" var="01d"></symbol><precipitation></precipitation><windDirection deg="240" code="WSW" name="West-southwest"></windDirection><windSpeed mps="3.82" name="Gentle Breeze"></windSpeed><temperature day="24.11" min="11.12" max="25.63" night="12.01" eve="24.25" morn="11.12"></temperature><pressure unit="hPa" value="955.35"></pressure><humidity value="49" unit="%"></humidity><clouds value="clear sky" all="0" unit="%"></clouds></time><time day="2016-05-28"><symbol number="801" name="few clouds" var="02d"></symbol><precipitation></precipitation><windDirection deg="251" code="WSW" name="West-southwest"></windDirection><windSpeed mps="6.61" name="Moderate breeze"></windSpeed><temperature day="20.66" min="10.44" max="20.66" night="11.98" eve="17.8" morn="10.44"></temperature><pressure unit="hPa" value="955.48"></pressure><humidity value="52" unit="%"></humidity><clouds value="few clouds" all="12" unit="%"></clouds></time><time day="2016-05-29"><symbol number="500" name="light rain" var="10d"></symbol><precipitation value="0.61" type="rain"></precipitation><windDirection deg="259" code="W" name="West"></windDirection><windSpeed mps="4.16" name="Gentle Breeze"></windSpeed><temperature day="18.78" min="11.19" max="20.01" night="13.02" eve="18.24" morn="11.19"></temperature><pressure unit="hPa" value="958.87"></pressure><humidity value="60" unit="%"></humidity><clouds value="few clouds" all="20" unit="%"></clouds></time><time day="2016-05-30"><symbol number="800" name="clear sky" var="01d"></symbol><precipitation></precipitation><windDirection deg="318" code="NW" name="Northwest"></windDirection><windSpeed mps="2.11" name="Light breeze"></windSpeed><temperature day="20.02" min="9.76" max="21.74" night="12.5" eve="21.12" morn="9.76"></temperature><pressure unit="hPa" value="960.15"></pressure><humidity value="55" unit="%"></humidity><clouds value="clear sky" all="0" unit="%"></clouds></time><time day="2016-05-31"><symbol number="500" name="light rain" var="10d"></symbol><precipitation></precipitation><windDirection deg="75" code="ENE" name="East-northeast"></windDirection><windSpeed mps="1.55" name=""></windSpeed><temperature day="25.2" min="11.03" max="25.87" night="14.12" eve="25.87" morn="11.03"></temperature><pressure unit="hPa" value="948.44"></pressure><humidity value="0" unit="%"></humidity><clouds value="clear sky" all="6" unit="%"></clouds></time><time day="2016-06-01"><symbol number="800" name="clear sky" var="01d"></symbol><precipitation></precipitation><windDirection deg="63" code="ENE" name="East-northeast"></windDirection><windSpeed mps="1.46" name="Calm"></windSpeed><temperature day="26.77" min="11.33" max="27.27" night="14.92" eve="27.27" morn="11.33"></temperature><pressure unit="hPa" value="948.35"></pressure><humidity value="0" unit="%"></humidity><clouds value="scattered clouds" all="27" unit="%"></clouds></time></forecast></weatherdata>

Thank you very much

asked by Ricardo Regueiro 26.05.2016 в 17:07

2 answers


The URL contains information within an XML, what you can do is use

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

That will allow you to parse the received String and search by Tag, that way you will only get the data you need. And already in the code:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(new File(filename)); //filename sería tu String
NodeList nList = doc.getElementsByTagName("time"); 
//tendrás que filtrar esta lista para que solo te entregue los datos del día deseado.
for (int i = 0; int < nList.getLength(); i++) {
Node nNode = nList.item(temp);
Element eElement = (Element) nNode;
if (eElement.getAttribute("day")=="2016-05-27"){
     System.out.println("Máxima : " 
              + eElement.getElementsByTagName("temperature").item(0).getAttribute("max");
     System.out.println("Mínima : " 
              + eElement.getElementsByTagName("temperature").item(0).getAttribute("min");

More information: link

answered by 26.05.2016 в 18:12

First of all, modifying the url of the webservice cnt=1 will bring only the information of today. (You should not add your KEY API, which should be private, now anyone can use it)

Now to obtain the maximum and minimum values you must parse the xml. You can use Java XML DOM .

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File( file ));
        Element root = document.getDocumentElement();
        NodeList nList = document.getElementsByTagName("temperature");
        for (int temp = 0; temp < nList.getLength(); temp++)
         Node node = nList.item(temp);
         System.out.println("");    //Just a separator
         if (node.getNodeType() == Node.ELEMENT_NODE)
            //Print each employee's detail
            Element eElement = (Element) node;


It may be that you have to make some adjustment to the previous code since I do not have an IDE at hand to validate.

A good XML DOM tutorial can be found here: link

answered by 26.05.2016 в 18:01