如何从标记名称更改的XML中获取API数据

时间:2019-06-13 22:21:31

标签: java xml api

因此,我尝试使用openweathermap API进行五天预报。它返回五天预报here

的xml

我一直在尝试使用代码NodeList nodeList = doc.getElementsByTagName("time");获取信息。如果您检查xml,则会看到标签<time>包含每2小时范围的预测。但问题是,由于名称实际上是<tag="date range""time range" to "time range + 3hrs">,因此我似乎无法从这些标记中抓取任何东西。

 try {
        DocumentBuilderFactory dbFactory = 
        DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(this.fiveDayForecastURL);
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("time");
        for (int i = 0; i < nodeList.getLength(); i++){
            Node node = nodeList.item(i);
            NamedNodeMap namedNodeMap = node.getAttributes();
            Node attr = namedNodeMap.getNamedItem("max");
            // just trying to grab anything from inside these tags
            // but ideally would want min and max temp for the range
            if (node.getNodeType() == Node.ELEMENT_NODE){
                System.out.println(attr);
                // always prints [time: null]
            }
            System.out.println(node);
            // always prints null 
        }
    } catch (ParserConfigurationException | IOException ex) {
        ex.printStackTrace();
    } catch (org.xml.sax.SAXException e) {
        e.printStackTrace();
    }

我确定我缺少一些代码行或某些内容,但是即使标签名称每次都更改,也有办法抓住时间标签之间的所有内容吗?谢谢

1 个答案:

答案 0 :(得分:0)

首先,我忘记了使用DOM解析器解析XML的麻烦。

您是否考虑过可以requesting the returned data as JSON解析gson

所以-您走在正确的轨道上,但是为了获取给定时间段内的最低/最高温度,您需要继续深入DOM层次结构。

温度是时间的子元素,因此您需要先获取它,然后从中获取min和max属性值。

类似的东西:

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

import java.io.IOException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;

public class Test {
    private static final String FIVE_DAY_FORECAST_URL = 
        "https://api.openweathermap.org/data/2.5/forecast?q=Denver&appid=8984d739fa91d7031fff0e84a3d2c520&mode=xml&units=imperial";

    private static final String TIME_ELEM = "time";
    private static final String TEMPERATURE_ELEM = "temperature";
    private static final String TIME_FROM_ATTR = "from";
    private static final String TIME_TO_ATTR = "to";
    private static final String TEMPERATURE_MIN_ATTR = "min";
    private static final String TEMPERATURE_MAX_ATTR = "max";

    private static void getWeatherForcast() {
        try {
            final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            final Document doc = dBuilder.parse(FIVE_DAY_FORECAST_URL);
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName(TIME_ELEM);
            for (int i = 0; i < nodeList.getLength(); i++) {
                final Node node = nodeList.item(i);
                final NamedNodeMap namedNodeMap = node.getAttributes();
                final Node fromAttr = namedNodeMap.getNamedItem(TIME_FROM_ATTR);
                final Node toAttr = namedNodeMap.getNamedItem(TIME_TO_ATTR);
                System.out.println("Time: " + fromAttr + " " + toAttr);
                final NodeList timeChildren = node.getChildNodes();
                for (int j = 0; j < timeChildren.getLength(); j++) {
                    final Node timeChild = timeChildren.item(j);
                    if (TEMPERATURE_ELEM.equals(timeChild.getNodeName())) {
                        final NamedNodeMap temperatureAttrMap = timeChild.getAttributes();
                        final String minTemp = temperatureAttrMap.getNamedItem(TEMPERATURE_MIN_ATTR).getNodeValue();
                        final String maxTemp = temperatureAttrMap.getNamedItem(TEMPERATURE_MAX_ATTR).getNodeValue();
                        System.out.println("min: " + minTemp + " max: " + maxTemp);
                    }
                }

            }
        } catch (ParserConfigurationException | IOException ex) {
            ex.printStackTrace();
        } catch (org.xml.sax.SAXException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        getWeatherForcast();
    }
}