【问题标题】:Unmarshal XML to struct and convert to slice将 XML 解组为结构并转换为切片
【发布时间】:2015-05-11 03:12:37
【问题描述】:

我在 Golang 中有一个简单的项目,我用它来学习这门语言。我正在开发的“服务”的主要目的是运行一个守护程序来保存作为 XML 公开的 URL。这样我就可以“生产”我自己的稍后阅读服务。到目前为止,一切都很好 :)。你可以在这里找到项目:https://github.com/rogierlommers/readinglist-golang

我使用 Gin-Gonic 作为提供 html 的框架。我已经设法读取了一个 xml 文件,将其解组,但现在我想在这个“东西”中添加一些新数据。换句话说:我认为我需要将其转换为切片,但我不知道如何管理。

F.e.端点r.GET("/add/:url") 应该使用函数 util.AddRecord 将新的 url 插入到切片中。但是怎么做呢?

[编辑] 基本上我的问题可以在这个 go playground 中查看:http://play.golang.org/p/Vx0s02E12R

【问题讨论】:

  • urlSlice = append(urlSlice, url)?
  • 谢谢;但我首先需要创建一个切片,对吧?我的函数ReadFileIntoSlice 正在返回未编组的数据。现在如何创建这些数据的切片?
  • 您需要更具体一些,我们不知道“事物”是什么,或者您为什么要将其转换为切片(什么?)。你的游乐场链接运行了,你想用它做什么?
  • Now how can I create a slice of this data? - 你有一个。 records.Records 是一个切片,包含 xml 中的每条记录 ..

标签: xml go slice


【解决方案1】:

在对您提出的问题的评论中:

我首先需要创建一个切片,对吧?

答案是肯定的,但你的 ReadingListRecords 结构中已经有一个切片:

type ReadingListRecords struct {
    XMLName xml.Name `xml:"records"`
    Records []Record `xml:"record"`
}

因此,您可以简单地在该切片上调用 append 并传入一个新的记录结构:

records.Records = append(record.Records, Record{xml.Name{"", "record"}, 4, "url", "2015-03-09 00:00:00"})

您还可以扩展 ReadingListRecords 结构的 API 以包含方便的 Append 函数:

type RecordSet interface {
    Append(record Record) error
}

func (records *ReadingListRecords) Append(record Record) error {
    newRecords := append(records.Records, record)

    if newRecords == nil {
        return errors.New("Could not append record")
    } else {
        records.Records = newRecords
        return nil
    }
}

添加接口似乎是个好主意,因为您希望将其用作多个应用程序中的服务。

my fork of your playground here

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2012-02-25
    • 1970-01-01
    • 2019-03-09
    • 2018-01-04
    • 2019-05-01
    • 2017-02-19
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多