golang xml Unmarshal

北慕城南 提交于 2021-01-29 11:33:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!