简体   繁体   English

我正在尝试使用 url xml 解析,但看起来我一直得到一个空的 xml

[英]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?我正在尝试从天气 API 中获取信息,尽管在我发出请求时我得到了响应,但是当我试图只获取响应的特定部分时,我每次都得到空响应有人可以帮忙吗? 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.我认为您正在尝试从 XML 标记中提取值,如果是这种情况,那么您就做错了。 Attributes object contains the attributes of a particular tag and to get the value you have to do some extra work. Attributes对象包含特定标签的属性,要获得该值,您必须做一些额外的工作。 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. current_tag变量将跟踪正在处理的当前标签。 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.注意:请不要在互联网上分享您的 API 密钥或密码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试从URL解析XML,但这仅显示了前3个元素,而并非全部 - I am trying to parse XML from URL but it just shows me only first 3 elements not all 我正在尝试解析XML文件,但是在解决收到的错误时遇到了一些麻烦 - I am trying to parse an XML file, but I am having some trouble fixing the errors I am receiving 我在尝试创建 XML 文件时不断出错 - I keep getting error while trying to create an XML file 我正在尝试在 android 中解析 Prefrences Xml 文件,但无法解析 getAttributesCount 方法总是返回零 - I am trying to parse Prefrences Xml file in android but not able to parse that getAttributesCount method is always returning zero 我正在尝试使用休眠xml映射连接到mysql数据库,但出现此错误 - I am trying to connect to a mysql database with hibernate xml mapping but I am getting this error 试图解析xml但得到malformedURLexception - Trying to parse a xml but getting malformedURLexception 我正在尝试在带有like子句的select查询中使用变量,但收到诸如无效标识符之类的错误 - I am trying to use variable in select query with like clause but getting an error like invalid identifier 我正在尝试使用JAXB将给定的XML文件解析为Common Class。 但是我什么都没得到 - I am trying to parse the given XML file into a Common Class using JAXB. But I do not get anything in the class 为什么我在从第三方URL读取xml时遇到此异常 - why i am getting this exception while reading xml from a thid party url 我究竟做错了什么? 尝试通过ServletContextListener在web.xml中使用context-param - What am I doing wrong? Trying to use context-param in web.xml with ServletContextListener
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM