golang xml Unmarshal

时间:2014-07-29 17:20:26

标签: xml go

我遵循以下示例并尝试解析xml并获取日期,日期,高级,文本和代码。 https://developer.yahoo.com/weather/#examples

解析不工作:

<yahooWeather>
<yweather:forecast day="Fri" date="18 Dec 2009" low="49" high="62" text="Partly Cloudy" code="30"/>
</yahooWeather>

解析工作正常:

<yahooWeather>
<yweather day="Fri" date="18 Dec 2009" low="49" high="62" text="Partly Cloudy" code="30"/>
</yahooWeather>

尝试阅读/理解xml stadards和golang xml包。同时请告诉我解决方案 或doc

我的代码: http://play.golang.org/p/4scMiXk6Dp

1 个答案:

答案 0 :(得分:1)

问题在于解决正确的XML命名空间,如this question中所述。在原始代码中,您已经声明了YahooWeather结构,如下所示:

type YahooWeather struct{

    Name yw `xml:"yweather"`

}

这不能按预期工作,因为yweatheryweather:forecast的命名空间,而不是实际的元素。为了捕获forecast元素,我们需要在XML字符串中包含命名空间定义。

var data1 = []byte(`
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <yweather:forecast day="Fri" date="18 Dec 2009" low="49" high="62" text="Partly Cloudy" code="30"/>
</rss>
`)

大概这是可以的,因为你真的要从服务器中提取这个RSS文件,命名空间定义将存在于真实数据中。然后,您可以像这样定义YahooWeather

type YahooWeather struct{

    Name yw `xml:"http://xml.weather.yahoo.com/ns/rss/1.0 forecast"`

}

如果您愿意,可以使用my fork of your playground