duan5731 2016-04-28 13:41
浏览 93

使用GO解析XML属性

I am pretty new to GO and I am having trouble extracting attribute values from XML documents. The code below produces the following output:

application ID:: "" application name:: ""

My assumption is that I am missing something when it comes to how to use tagging and I would really appreciate it if someone could point me in the right direction.

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
", portfolio.Apps[0].app_id)
fmt.Printf("application name:: %q
", portfolio.Apps[0].app_name)
  • 写回答

1条回答 默认 最新

  • duanhui7329 2016-04-28 14:07
    关注

    In order to be able to get the elements out you have to have "exported" fields, meaning that app_id and app_name in the App struct should start with a capital letter. In addition, your app_name field is also missing a ,attr in its xml field tag. See below for a working example of your code. I've added comments on the lines that require some changes.

    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
    ", portfolio.Apps[0].App_id)       // the corresponding changes here for App
        fmt.Printf("application name:: %q
    ", portfolio.Apps[0].App_name)   // the corresponding changes here for App
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度