2 回答
TA贡献1863条经验 获得超2个赞
试试这个游乐场。我使用此工具作弊并帮助我从XML数据生成Go类型。
package main
import (
"encoding/xml"
"fmt"
)
type Status struct {
XMLName xml.Name `xml:"status"`
Text string `xml:",chardata"`
Authorized string `xml:"authorized"`
Plan string `xml:"plan"`
UsageReports struct {
Text string `xml:",chardata"`
UsageReport []struct {
Text string `xml:",chardata"`
Metric string `xml:"metric,attr"`
Period string `xml:"period,attr"`
PeriodStart string `xml:"period_start"`
PeriodEnd string `xml:"period_end"`
MaxValue string `xml:"max_value"`
CurrentValue string `xml:"current_value"`
} `xml:"usage_report"`
} `xml:"usage_reports"`
}
func main() {
status := Status{}
err := xml.Unmarshal([]byte(xmlStr), &status)
if err != nil {
panic(err)
}
fmt.Println(status.UsageReports.UsageReport[0].MaxValue)
}
const xmlStr = `<?xml version="1.0" encoding="UTF-8"?><status><authorized>true</authorized><plan>Basic</plan><usage_reports><usage_report metric="hits" period="day"><period_start>2021-07-20 00:00:00 +0000</period_start><period_end>2021-07-21 00:00:00 +0000</period_end><max_value>1000000</max_value><current_value>0</current_value></usage_report><usage_report metric="hits.82343" period="day"><period_start>2021-07-20 00:00:00 +0000</period_start><period_end>2021-07-21 00:00:00 +0000</period_end><max_value>1000000</max_value><current_value>0</current_value></usage_report></usage_reports></status>`
TA贡献1942条经验 获得超3个赞
为了获得字段的值,请根据姆科普里瓦的建议进行修改。Usagesxml:"usage_reports"xml:"usage_reports>usage_report"
package main
import (
"encoding/xml"
"fmt"
)
type UsageReport struct {
Metric string `xml:"metric,attr"`
Period string `xml:"period,attr"`
Start string `xml:"period_start"`
End string `xml:"period_end"`
Max int64 `xml:"max_value"`
Current int64 `xml:"current_value"`
}
type AuthResponse struct {
Status xml.Name `xml:"status"`
Authorized bool `xml:"authorized"`
Plan string `xml:"plan"`
Usages []UsageReport `xml:"usage_reports>usage_report"`
}
var data = []byte(`<?xml version="1.0" encoding="UTF-8"?>
<status>
<authorized>true</authorized>
<plan>Basic</plan>
<usage_reports>
<usage_report metric="hits" period="day">
<period_start>2021-07-20 00:00:00 +0000</period_start>
<period_end>2021-07-21 00:00:00 +0000</period_end>
<max_value>1000000</max_value>
<current_value>0</current_value>
</usage_report>
<usage_report metric="hits.82343" period="day">
<period_start>2021-07-20 00:00:00 +0000</period_start>
<period_end>2021-07-21 00:00:00 +0000</period_end>
<max_value>1000000</max_value>
<current_value>0</current_value>
</usage_report>
</usage_reports>
</status>
`)
func main() {
r := AuthResponse{}
if err := xml.Unmarshal(data, &r); err != nil {
panic(err)
}
fmt.Println(r)
}
输出:
{{ } true Basic [{hits day 2021-07-20 00:00:00 +0000 2021-07-21 00:00:00 +0000 1000000 0} {hits.82343 day 2021-07-20 00:00:00 +0000 2021-07-21 00:00:00 +0000 1000000 0}]}
- 2 回答
- 0 关注
- 154 浏览
添加回答
举报
