Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 15
  1. #1

    [Java] Problema con Google Weather API

    salve!
    sto cercando di reperire informazioni da Google Weather API attravers java e XPath.
    ma ho dei problemi:
    codice:
    public class CheckWeather {
    
        public void takeWeather(String city) throws ParserConfigurationException, MalformedURLException, IOException, SAXException, XPathExpressionException {
            URL url = new URL("http://www.google.com/ig/api?weather=roma&hl=it");
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            InputSource inputSource = new InputSource(in);
            inputSource.setEncoding("ISO-8859-1");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputSource);
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expr = xpath.compile("//weather/forecast_information/"); // ECCEZIONE
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getNodeValue());
            }
        }
    }
    mi viene sollevata un'eccezione alla riga che ho commentato.
    probabilmente nn ho ben capito io come interrogare la risposta del servizio che ha una forma del genere:
    codice:
    <xml_api_reply version="1">
     <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0>
    
       <forecast_information><city data="Rome, Lazio"/><postal_code data="roma"/>
          <latitude_e6 data=""/>
          <longitude_e6 data=""/>
          <forecast_date data="2012-01-28"/>
          <current_date_time data="1970-01-01 00:00:00 +0000"/>
          <unit_system data="SI"/></forecast_information>
        <current_conditions>
           <condition data="Nuvoloso"/>
           <temp_f data="45"/>
           <temp_c data="7"/>
           <humidity data="Umidità: 81%"/>
           <icon data="/ig/images/weather/cloudy.gif"/>
           <wind_condition data="Vento: E a 8 km/h"/>
        </current_conditions>
    ..........
    l'inizio dell'errore è questo:
    codice:
    javax.xml.transform.TransformerException: È previsto un passo di posizione dopo il token '/' o '//'.
    solo che nn ho capito come risolverlo.

  2. #2
    ho fatto diverse prove e nn riesco bene a capire.
    ad esempio:
    codice:
    public void takeWeather() throws ParserConfigurationException, MalformedURLException, IOException, SAXException, XPathExpressionException {
            URL url = new URL("http://www.google.com/ig/api?weather=roma&hl=it");
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            InputSource inputSource = new InputSource(in);
            inputSource.setEncoding("ISO-8859-1");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputSource);
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression current = xpath.compile("//xml_api_reply/weather/forecast_information");
            Object resultCurrent = current.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) resultCurrent;
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getChildNodes());
            }
        }
    dovrebbe restituire tutti i sotto nodi di forecast_information e invece mi stampa questo:
    codice:
    [forecast_information: null]
    poi ho notato che in effetti i vari nodi nn hanno valori ma solo attributi.
    allora ho provato questo:
    codice:
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getAttributes());
            }
    
    
    com.sun.org.apache.xerces.internal.dom.AttributeMap@377f4fbb
    insomma c'è qualcosa che nn quadra.
    nessuno ha un'idea?

  3. #3
    Utente di HTML.it
    Registrato dal
    Feb 2007
    Messaggi
    4,157
    non conosco la libreria, ma dal messaggio vedo che potrebbe trattarsi di una stringa mal formata, c'è un esempio nelle API di come dovrebbe essere il token parsato dalle API?
    RTFM Read That F*** Manual!!!

  4. #4
    purtroppo gli unici esempi concreti che ho trovato sono in PHP.
    da li mi è venuta l'idea di usare XPath, ma nn è obbligatorio.
    il mio problema è che nn riesco a leggere quel formato XML.
    avevo provato anche con gli oggetti Element della libreria import org.w3c.dom.Element.

  5. #5
    tanto per provare senza usare XPath:
    codice:
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.XPathExpressionException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    public class CheckWeather {
    
        public void takeWeather() throws ParserConfigurationException, MalformedURLException, IOException, SAXException, XPathExpressionException {
            URL url = new URL("http://www.google.com/ig/api?weather=roma&hl=it");
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            InputSource inputSource = new InputSource(in);
            inputSource.setEncoding("ISO-8859-1");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputSource);
            doc.getDocumentElement().normalize();
            NodeList forecastInformation = doc.getElementsByTagName("forecast_information");
            for (int i = 0; i < forecastInformation.getLength(); i++) {
                Node node = forecastInformation.item(i);
                Element element = (Element) node;
                System.out.println(element.getNodeValue());
                System.out.println(element.getAttributes());
                System.out.println(element.getChildNodes());
                System.out.println(element.getNodeName());
            }
        }
    }
    questi sono i riultati:
    codice:
    null
    com.sun.org.apache.xerces.internal.dom.AttributeMap@1071f57
    [forecast_information: null]
    forecast_information
    volevo postare il codice XML che restituisce Google, ma penso sia meglio andarci direttamente via browser: http://www.google.com/ig/api?weather=roma&hl=it

  6. #6
    s così si può dire, in un modo avrei risolto:
    codice:
    public class CheckWeather {
    
        public void takeWeather() throws ParserConfigurationException, MalformedURLException, IOException, SAXException, XPathExpressionException {
            URL url = new URL("http://www.google.com/ig/api?weather=roma&hl=it");
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            InputSource inputSource = new InputSource(in);
            inputSource.setEncoding("ISO-8859-1");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputSource);
            doc.getDocumentElement().normalize();
            // NODO CITY
            NodeList nlCity = doc.getElementsByTagName("city");
            Node nCity = nlCity.item(0);
            Element eCity = (Element) nCity;
            System.out.println(eCity.getAttribute("data"));
    
            // NODO CONDITION
            NodeList nlCond = doc.getElementsByTagName("condition");
            Node nCond = nlCond.item(0);
            Element eCond = (Element) nCond;
            System.out.println(eCond.getAttribute("data"));
        }
    }
    cert nn è molto comodo visto che nn riesco a usare nessun autmatismo ma sto scrivendo a mano praticamente tutti singoli dati che mi servono.

  7. #7
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    non ti conviene usare un array e ciclare su quello? Sia mai che cambiano i nomi dei tag, devi solo mettere mano all'array
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  8. #8
    intendi una cosa del genere?:
    codice:
            NodeList nodeList = null;
            String[] arrayNodes = {"city", "condition"};
            for (int i = 0; i < arrayNodes.length; i++) {
                nodeList = doc.getElementsByTagName(arrayNodes[i]);
                Node n = nodeList.item(0);
                Element e = (Element) n;
            }
    bhe si ovviamente è più comodo.
    grazie per il consiglio!

  9. #9
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    esatto! Poi al limite, vedi se non ti conviene creare un oggetto (o un paio) appositi, visto che ci sono dei gruppi ripetuti (le previsioni a 3 giorni per intenderci)
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  10. #10
    ok adesso cerco di organizzarmi meglio.
    grazie per il consiglio!!!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.