为什么groovy每个函数不在另一个内部迭代

时间:2017-08-01 06:11:33

标签: groovy iteration xmlslurper stringwriter markupbuilder

为什么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

1 个答案:

答案 0 :(得分:0)

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

source code of groovycsv library

static Iterator parseCsv(Map args = [:], String csv) {
    new CsvParser().parse(args, csv)
}