[英]golang xml Unmarshal
我正在下面的示例,并尝试解析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标准和golang xml包。 同时,请向我建议解决方案或文档
我的代码: http : //play.golang.org/p/4scMiXk6Dp
问题是解决正确的XML名称空间,如本问题所述 。 在原始代码中,您已经声明了YahooWeather
结构,如下所示:
type YahooWeather struct{
Name yw `xml:"yweather"`
}
这不能按预期方式工作,因为yweather
是yweather: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"`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.