问题
I am following the below example and trying to parse the xml and get day, date, high ,text, code. https://developer.yahoo.com/weather/#examples
parsing Not working:
<yahooWeather>
<yweather:forecast day="Fri" date="18 Dec 2009" low="49" high="62" text="Partly Cloudy" code="30"/>
</yahooWeather>
parsing Working fine:
<yahooWeather>
<yweather day="Fri" date="18 Dec 2009" low="49" high="62" text="Partly Cloudy" code="30"/>
</yahooWeather>
trying to read/understand xml stadards and golang xml package. In mean time please suggest me the solution or doc
My code: http://play.golang.org/p/4scMiXk6Dp
回答1:
The problem is addressing the correct XML namespace, as described in this question. In your original code, you had declared the YahooWeather
struct like this:
type YahooWeather struct{
Name yw `xml:"yweather"`
}
This doesn't work as expected because yweather
is the namespace of yweather:forecast
, not the actual element. In order to capture the forecast
element, we need to include the namespace definition in the XML string.
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>
`)
Presumably this is ok because you're really going to be pulling this RSS file from the server, and the namespace definitions will be there in the real data. You can then define YahooWeather
like this:
type YahooWeather struct{
Name yw `xml:"http://xml.weather.yahoo.com/ns/rss/1.0 forecast"`
}
You can play with my fork of your playground if you'd like.
来源:https://stackoverflow.com/questions/25021322/golang-xml-unmarshal