我有这个示例代码,它解析来自雅虎的 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