英文:
golang xml Unmarshal
问题
我正在遵循下面的示例,尝试解析 XML 并获取 day、date、high、text、code。
解析不起作用的示例:
<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
英文:
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
得分: 1
问题是如何正确处理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"`
}
如果你愿意,可以尝试使用我对你的playground的修改版本。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论