简体   繁体   中英

I am trying to use a url xml parse but it looks like i keep getting an empty xml

I am trying to get info from a weather API called even though when i am making the request i am getting a response, but when i am trying to get only a specific part of the response i get null response every time can someone help? here is the code for my handler :

package weathercalls;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class Handler extends DefaultHandler
{

    // Create three array lists to store the data
    public ArrayList<Integer> lows = new ArrayList<Integer>();
    public ArrayList<Integer> highs = new ArrayList<Integer>();
    public ArrayList<String> regions = new ArrayList<String>();


    // Make sure that the code in DefaultHandler's
    // constructor is called:
    public Handler()
    {
        super();
    }


    /*** Below are the three methods that we are extending ***/

    @Override
    public void startDocument()
    {
        System.out.println("Start document");
    }


    @Override
    public void endDocument()
    {
        System.out.println("End document");
    }


    // This is where all the work is happening:
    @Override
    public void startElement(String uri, String name, String qName, Attributes atts)
    {
        if(qName.compareTo("region") == 0)
        {
            String region = atts.getLocalName(0);
            System.out.println("Day: " + region);
            this.regions.add(region);
        }
        if(qName.compareToIgnoreCase("wind_degree") == 0)
        {
            int low =  atts.getLength();
            System.out.println("Low: " + low);
            this.lows.add(low);
        }
        if(qName.compareToIgnoreCase("high") == 0)
        {
            int high = Integer.parseInt(atts.getValue(0));
            System.out.println("High: " + high);
            this.highs.add(high);
        }

    }
}

and here is my main file code :

package weathercalls;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;




public class weatherCalls {


    public static void main(String[] args) throws Exception {

        //Main url
        String main_url = "http://api.weatherapi.com/v1/";

        //Live or Weekly forecast
        String live_weather = "current.xml?key=";
        //String sevendays_weather = "orecast.xml?key=";

        //API Key + q
        String API_Key = "c2e285e55db74def97f151114201701&q=";

        //Location Setters
        String location = "London";


        InputSource inSource = null;
        InputStream in = null;

        XMLReader xr = null;
        /**
        URL weather = new URL(main_url + live_weather + API_Key + location);
        URLConnection yc = weather.openConnection();
        BufferedReader in1 = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));

        String inputLine;

        while ((inputLine = in1.readLine()) != null)
                System.out.println(inputLine);
        in1.close();**/

        try
        {
            // Turn the string into a URL object
            String complete_url = main_url + live_weather + API_Key + location;
            URL urlObject = new URL(complete_url);

            // Open the stream (which returns an InputStream):
            in = urlObject.openStream();

            /** Now parse the data (the stream) that we received back ***/

            // Create an XML reader
            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            SAXParser parser = parserFactory.newSAXParser();
            xr = parser.getXMLReader();

            // Tell that XML reader to use our special Google Handler
            Handler ourSpecialHandler = new Handler();
            xr.setContentHandler(ourSpecialHandler);

            // We have an InputStream, but let's just wrap it in
            // an InputSource (the SAX parser likes it that way)
            inSource = new InputSource(in);

            // And parse it!
            xr.parse(inSource);
            System.out.println(complete_url);
            System.out.println(urlObject);
            System.out.println(in);
            System.out.println(xr);
            System.out.println(inSource);
            System.out.println(parser);

        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
        catch(SAXException se)
        {
            se.printStackTrace();
        }

    }
    }



and this is my console print:

Start document
Day: null
Low: 0
End document
http://api.weatherapi.com/v1/current.xml?key=c2e285e55db74def97f151114201701&q=London
http://api.weatherapi.com/v1/current.xml?key=c2e285e55db74def97f151114201701&q=London
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@2471cca7
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser@5fe5c6f
org.xml.sax.InputSource@6979e8cb
com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl@763d9750

I think you are trying to extract the values from the XML tags and if it is the case then you are doing it wrong. Attributes object contains the attributes of a particular tag and to get the value you have to do some extra work. Similar to the start of a tag, there are separate events for the contents and the end of a tag. current_tag variable will keep track of the current tag being processed. Below is a sample code:

class Handler extends DefaultHandler {

// Create three array lists to store the data
public ArrayList<Integer> lows = new ArrayList<Integer>();
public ArrayList<Integer> highs = new ArrayList<Integer>();
public ArrayList<String> regions = new ArrayList<String>();


// Make sure that the code in DefaultHandler's
// constructor is called:
public Handler() {
    super();
}


/*** Below are the three methods that we are extending ***/

@Override
public void startDocument() {
    System.out.println("Start document");
}


@Override
public void endDocument() {
    System.out.println("End document");
}

//Keeps track of the current tag;
String currentTag = "";

// This is where all the work is happening:
@Override
public void startElement(String uri, String name, String qName, Attributes atts) {
    //Save the current tag being handled
    currentTag = qName;
}

//Detect end tag
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    //Reset it
    currentTag = "";
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
    //Rules based on current tag
    switch (currentTag) {
        case "region":
            String region = String.valueOf(ch, start, length);
            this.regions.add(region);
            System.out.println("Day: " + region);
            break;
        case "wind_degree":
            int low = Integer.parseInt(String.valueOf(ch, start, length));
            System.out.println("Low: " + low);
            this.lows.add(low);
            break;
        case "high":
            int high = Integer.parseInt(String.valueOf(ch, start, length));
            System.out.println("High: " + high);
            this.highs.add(high);
            break;
    }
}}

NOTE: Please refrain from sharing your API keys or passwords on the internet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM