用GO解析XML属性
问题描述:
我对GO很新,我无法从XML文档中提取属性值。下面的代码产生以下输出:用GO解析XML属性
应用程序ID ::“” 应用程序名称::“”
我的假设是,我失去了一些东西,当谈到如何使用标记,我真的很感激如果有人能指引我正确的方向。
data:=`<?xml version="1.0" encoding="UTF-8"?>
<applist>
<app app_id="1234" app_name="abc"/>
<app app_id="5678" app_name="def"/>
</applist> `
type App struct {
app_id string `xml:"app_id,attr"`
app_name string `xml:"app_name"`
}
type AppList struct {
XMLName xml.Name `xml:"applist"`
Apps []App `xml:"app"`
}
var portfolio AppList
err := xml.Unmarshal([]byte(data), &portfolio)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("application ID:: %q\n", portfolio.Apps[0].app_id)
fmt.Printf("application name:: %q\n", portfolio.Apps[0].app_name)
答
为了能够获得这些元件,你必须有“出口”领域,这意味着在App
结构app_id
和app_name
应该以大写字母开头。另外,您的app_name
字段在其xml字段标记中也缺少,attr
。请参阅下面的代码的工作示例。我在需要更改的行上添加了评论。
package main
import (
"fmt"
"encoding/xml"
)
func main() {
data:=`
<?xml version="1.0" encoding="UTF-8"?>
<applist>
<app app_id="1234" app_name="abc"/>
<app app_id="5678" app_name="def"/>
</applist>
`
type App struct {
App_id string `xml:"app_id,attr"` // notice the capitalized field name here
App_name string `xml:"app_name,attr"` // notice the capitalized field name here and the `xml:"app_name,attr"`
}
type AppList struct {
XMLName xml.Name `xml:"applist"`
Apps []App `xml:"app"`
}
var portfolio AppList
err := xml.Unmarshal([]byte(data), &portfolio)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("application ID:: %q\n", portfolio.Apps[0].App_id) // the corresponding changes here for App
fmt.Printf("application name:: %q\n", portfolio.Apps[0].App_name) // the corresponding changes here for App
}
完美。谢谢您的帮助。 –