0

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

vrbilgi
  • 5,703
  • 12
  • 44
  • 60

1 Answers1

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.

Community
  • 1
  • 1
Austin Mullins
  • 7,307
  • 2
  • 33
  • 48
  • note that the second Unmarshal in your example is silently failing, and printing the same struct that was used in the first Unmarshal. – JimB Jul 29 '14 at 17:49
  • @JimB Yup. I suspected that might be happening, so I made a new variable `c` and tried unmarshaling the `yweather` version. It failed, as expected. – Austin Mullins Jul 29 '14 at 18:02
  • I can only say that I had no idea you could add namespace definitions to the `xml` decoration field like that! That's simply amazing! – Gwyneth Llewelyn May 04 '22 at 10:39