首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在groovy中使用追加节点操作列表

在groovy中使用追加节点操作列表
EN

Stack Overflow用户
提问于 2019-11-13 12:48:29
回答 1查看 203关注 0票数 1

我正在尝试将一个xml文件解析为一个列表。然后在列表中使用嵌套循环并追加新节点。

这是我写的代码

代码语言:javascript
复制
    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 

我得到的输出是

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-13 13:35:18

您正在使用流生成器,这是懒惰的。这意味着,在执行过程中,它获得全局变量str的实际(最近)值。

为了使其正确,您必须缩小变量的范围:

代码语言:javascript
复制
          // 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)}
                } }

然后打印出来:

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58837511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档