我正在尝试将一个xml文件解析为一个列表。然后在列表中使用嵌套循环并追加新节点。
这是我写的代码
import java.util.HashMap;
import groovy.xml.*;
def scresp = '''
<root>
<Customer>
<CustomerID>100</CustomerID>
</Customer>
<Customer>
<CustomerID>101</CustomerID>
</Customer>
<Customer>
<CustomerID>102</CustomerID>
</Customer>
</root>'''
def reslist = new XmlSlurper().parseText(scresp)
def str = ''
reslist.each
{line ->
line.Customer.eachWithIndex { cust, idx ->
str = "Count: " + idx
println str
cust.appendNode{
Count(idx)
Sample(str)}
} }
def updatedPayload = new StreamingMarkupBuilder().bind { mkp.yield reslist }.toString()
println updatedPayload 我得到的输出是
Count: 0
Count: 1
Count: 2
<root>
<Customer>
<CustomerID>100</CustomerID>
<Sample>Count: 2</Sample>
</Customer>
<Customer>
<CustomerID>101</CustomerID>
<Sample>Count: 2</Sample>
</Customer>
<Customer>
<CustomerID>102</CustomerID>
<Sample>Count: 2</Sample>
</Customer>
</root>我的问题是为什么只有最后一个值'Count: 2‘被添加到xml中,尽管println返回正确的值Count: 0,Count: 1& Count: 2?
发布于 2019-11-13 13:35:18
您正在使用流生成器,这是懒惰的。这意味着,在执行过程中,它获得全局变量str的实际(最近)值。
为了使其正确,您必须缩小变量的范围:
// def str = '' // << delete this line
reslist.each
{line ->
line.Customer.eachWithIndex { cust, idx ->
String str = "Count: " + idx // declare the variable here
println str
cust.appendNode{
Count(idx)
Sample(str)}
} }然后打印出来:
<root>
<Customer><CustomerID>100</CustomerID><Count>0</Count><Sample>Count: 0</Sample></Customer>
<Customer><CustomerID>101</CustomerID><Count>1</Count><Sample>Count: 1</Sample></Customer>
<Customer><CustomerID>102</CustomerID><Count>2</Count><Sample>Count: 2</Sample></Customer>
</root>https://stackoverflow.com/questions/58837511
复制相似问题