在GO中创建一个用于读取大字符串的流。

huangapple go评论141阅读模式
英文:

Create a stream to read a huge string in GO

问题

我有一个巨大的 XML 存储在一个变量中,并且有一个函数用于解码这个 XML。我不能使用 unmarshal,因为在某个时刻我需要读取一个元素并立即将其添加到数据库中。

示例:

db := mongo.Connect()

decoder := xml.NewDecoder(resp.Body)
defer resp.Body.Close()

for {
    token, _ := decoder.Token()
    if token == nil {
        break
    }

    switch se := token.(type) {
    case xml.StartElement:
    ...
}

但现在我需要从一个字符串中读取。所以我不再有 resp.Body,而是一个字符串。NewDecoder() 函数接收一个 io.Reader,所以我认为我可以从一个流中读取。我该如何做到这一点?

英文:

I have a huge xml in a variable and a function to decode this xml. I can't use unmarshal because at a certain momment I need to read an element and add it immediately in the db.

Example:

db := mongo.Connect()

decoder := xml.NewDecoder(resp.Body)
defer resp.Body.Close()

for {
    token, _ := decoder.Token()
    if token == nil {
        break
    }

    switch se := token.(type) {
    case xml.StartElement:
    ...
}

But now I need to read from a string. So I don't have the resp.Body anymore but a string. The NewDecoder() function receives an io.Reader, so I think I can in read from a stream. How can I do this??

答案1

得分: 5

使用strings.NewReader方法将任何字符串转换为io.Reader

reader := strings.NewReader("some string")
英文:

Turn any string into an io.Reader with the strings.NewReader method:

reader := strings.NewReader("some string")

huangapple
  • 本文由 发表于 2017年9月5日 00:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/46041256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定