0

为什么 groovy .each 函数只有一次迭代,而它位于另一次迭代中,如下面的代码所示?

代码:

@Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
def input = "input.xml"
def xml = new XmlSlurper().parse(input)
df = new FileReader("file.csv")
def writer = new StringWriter()
def data = parseCsv(df, readFirstLine: true)
new MarkupBuilder(writer).root {
    xml.children().each {
        it.attributes()
        println ("Here I am")
        data.eachWithIndex { row,id->                     
            println ("This line should be iterated all time") // but iterated only one time             
        }
    }
}

输出是这样的,

    Here I am
    This line should be iterated all time
    This line should be iterated all time
    This line should be iterated all time
    Here I am
    Here I am

预期输出:

Here I am
This line should be iterated all time
This line should be iterated all time
This line should be iterated all time
Here I am
This line should be iterated all time
This line should be iterated all time
This line should be iterated all time
Here I am
This line should be iterated all time
This line should be iterated all time
This line should be iterated all time
4

1 回答 1

0

那是因为parseCsv返回一个Iterator,而不是一个Iterable

请参阅groovycsv 库的源代码

static Iterator parseCsv(Map args = [:], String csv) {
    new CsvParser().parse(args, csv)
}
于 2017-08-01T06:41:18.373 回答