使用命名空间进行XML解析

时间:2013-08-13 13:12:32

标签: android xml xml-parsing

我有这个示例代码解析来自雅虎的XML天气数据,我必须做什么以某种方式简化它,并且可能使它循环,但我无法弄清楚如何。 XML有命名空间,这是问题的一部分,这是我到目前为止所做的:

private MyWeather parseWeather(Document doc) {

        MyWeather myWeather = new MyWeather();
        myWeather.description = doc.getElementsByTagName("description").item(0).getTextContent();
        Node locationNode = doc.getElementsByTagName("yweather:location").item(0);
        myWeather.city = locationNode.getAttributes().getNamedItem("city").getNodeValue().toString();
        myWeather.region = locationNode.getAttributes().getNamedItem("region").getNodeValue().toString();
        myWeather.country = locationNode.getAttributes().getNamedItem("country").getNodeValue().toString();
        Node windNode = doc.getElementsByTagName("yweather:wind").item(0);
        myWeather.windChill = windNode.getAttributes().getNamedItem("chill").getNodeValue().toString();
        myWeather.windDirection = windNode.getAttributes().getNamedItem("direction").getNodeValue().toString();
        myWeather.windSpeed = windNode.getAttributes().getNamedItem("speed").getNodeValue().toString();
        Node astronomyNode = doc.getElementsByTagName("yweather:astronomy").item(0);
        myWeather.sunrise = astronomyNode.getAttributes().getNamedItem("sunrise").getNodeValue().toString();
        myWeather.sunset = astronomyNode.getAttributes().getNamedItem("sunset").getNodeValue().toString();
        Node conditionNode = doc.getElementsByTagName("yweather:condition").item(0);
        myWeather.conditiontext = conditionNode.getAttributes().getNamedItem("text").getNodeValue().toString();
        myWeather.conditiondate = conditionNode.getAttributes().getNamedItem("date").getNodeValue().toString();

        return myWeather;
    }

在MyWeather上我有这个

public class MyWeather {
    public String description;
    public String city;
    public String region;
    public String country;
    public String windChill;
    public String windDirection;
    public String windSpeed;
    public String sunrise;
    public String sunset;
    public String conditiontext;
    public String conditiondate;

    public String toString() {

        return "\n- " + description + " -\n\n" + "city: " + city + "\n" + "region: " + region + "\n" + "country: " + country + "\n\n"

        + "Wind\n" + "chill: " + windChill + "\n" + "direction: " + windDirection + "\n" + "speed: " + windSpeed + "\n\n"

        + "Sunrise: " + sunrise + "\n" + "Sunset: " + sunset + "\n\n"

        + "Condition: " + conditiontext + "\n" + conditiondate + "\n";

    }
}

我正在解析的链接就是这个 - http://weather.yahooapis.com/forecastrss?w=838804

1 个答案:

答案 0 :(得分:0)