加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Groovy中使用XML MarkupBuilder动态添加多个XML元素/容器

发布时间:2020-12-14 16:30:23 所属栏目:大数据 来源:网络整理
导读:我正在使用Groovy MarkupBuilder生成 XML. 所需的XML是这种形式(简化): Order StoreID / City / Items Item ItemCode / UnitPrice / Quantity / /Item /Items/Order 数据存储在Excel文件中,易于访问.我的Groovy脚本解析Excel并生成XML. 例如 import groovy.
我正在使用Groovy MarkupBuilder生成 XML.

所需的XML是这种形式(简化):

<Order>
  <StoreID />
  <City />
  <Items>
    <Item>
      <ItemCode />
      <UnitPrice />
      <Quantity />
    </Item>
  </Items>
</Order>

数据存储在Excel文件中,易于访问.我的Groovy脚本解析Excel并生成XML.

例如

import groovy.xml.*
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.Order{
  StoreID("Store1")
  City("New York")
  Items(){
    Item(){
      ItemCode("LED_TV")
      UnitPrice("800.00")
      Quantity("2")
    }
  }
}

“项目”内可以有多个“项目”容器.

我的问题是:
假设我们要生成具有10个项目的Order XML.有没有办法在“items”容器中写一个像for循环的内容?这样,我们不需要为10个不同的项目编写MarkupBuilder代码.

有一个类似的问题Adding dynamic elements and attributes to groovy MarkupBuilder or StreamingMarkupBuilder.但它不讨论循环.

解决方法

是的,有一种使用循环的方法.在这里扩展你的例子:

import groovy.xml.*
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

//List of items represented as a map
def items = [[itemCode: "A",unitPrice: 10,quantity: 2],[itemCode: "B",unitPrice: 20,quantity: 3],[itemCode: "C",unitPrice: 30,quantity: 4],[itemCode: "D",unitPrice: 40,quantity: 6],[itemCode: "E",unitPrice: 50,quantity: 5]]

xml.Order{
  StoreID("Store1")
  City("New York")
  Items{
    //Loop through the list.
    //make sure you are using a variable name instead of using "it"
    items.each{item->
      Item{
        ItemCode(item.itemCode)
        UnitPrice(item.unitPrice)
        Quantity(item.quantity)
      }
    }
  }
}

println writer

应该给你你期待的东西

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读