gpt4 book ai didi

xml - 使用 GO 解析 XML 属性

转载 作者:IT王子 更新时间:2023-10-29 01:52:39 30 4
gpt4 key购买 nike

我是 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_idapp_name > struct 应该以大写字母开头。此外,您的 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
}

关于xml - 使用 GO 解析 XML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916504/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com