使用GO解析XML属性

1 xml go

我是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)
Run Code Online (Sandbox Code Playgroud)

Wil*_*l C 5

为了能够获得这些元件,你必须有"出口"领域,这意味着app_idapp_nameApp结构应该以大写字母开头.此外,您的app_name字段,attr在其xml字段标记中也缺少a .有关代码的工作示例,请参见下文.我在需要进行一些更改的行上添加了注释.

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
}
Run Code Online (Sandbox Code Playgroud)