-2

基本上我在底部有一些这样的代码。这会创建很多列表,但是否可以将所有这些列表放在地图中?另外,我在我的 for 循环中访问每个索引,因此是否可以在其中包含列表的地图中访问这些索引?我只是想实现更短的代码并且可能更高效。

//Create our lists
def htmlList = []
def pixProductList = []
def pixLanguageList = []
def pixOffercodeList = []
def pixVIDList = []
def pixStartDateList = []
def pixEndDateList = []
def pixContactList = []
def pixPublisherList = []
def newPixelList = []

//Parse the file
String file = new File('grails-app/controllers/pixel/editor/tool/trackingPixels.xml').text
newPixelList = StringUtils.substringsBetween(file, "<pixelNew", "</pixelNew>")

//Access each element in newPixelList 
for(int i =0; i < newPixelList.size(); i++){
    String newPixel = newPixelList[i]
    htmlList[i] = StringUtils.substringBetween(newPixel, "<html>", "</html>")
    pixProductList[i] = StringUtils.substringBetween(newPixel, "<product>", "</product>")
    pixLanguageList[i] = StringUtils.substringBetween(newPixel, "<lang>", "</lang>")
    pixOffercodeList[i] = StringUtils.substringBetween(newPixel, "<offercode>", "</offercode>")
    pixVIDList[i] = StringUtils.substringBetween(newPixel, "<vid>", "</vid>")
    pixStartDateList[i] = StringUtils.substringBetween(newPixel, "<startDate>", "</startDate>")
    pixEndDateList[i] = StringUtils.substringBetween(newPixel, "<endDate>", "</endDate>")
    pixContactList[i] = StringUtils.substringBetween(newPixel, "<contact>", "</contact>")
    pixPublisherList[i] = StringUtils.substringBetween(newPixel, "<publisher>", "</publisher>")
    }
4

1 回答 1

2

首先,您实际上可以使用 XML slurper 并使用它来代替这种字符串操作。

def htmlList = []
def pixProductList = []
def pixLanguageList = []
def pixOffercodeList = []
def pixVIDList = []
def pixStartDateList = []
def pixEndDateList = []
def pixContactList = []
def pixPublisherList = []
def newPixelList = []

File file = new File('grails-app/controllers/pixel/editor/tool/trackingPixels.xml')
def xmlFile = new XmlSlurper().parse(file)
def records = xmlFile.pixelNew //Assuming pixelNew is the top level node

records.each {
    htmlList.add(it.html.text())
    pixProductList.add(it.product.text())
    ...
}

然后你可以创建一个类来存储这些数据并在构造函数中填充数据

class WhateverYouWant {
  String html
  String product
  ...

  public WhateverYouWant(NodeChild record) {
      this.html = record.html.text()
      this.product = record.product.text()
      ...
  }
}

然后你可以简单地做:

List<WhateverYouWant> items = []

xmlFile = new XmlSlurper().parse(file)
def records = xmlFile.pixelNew //Assuming pixelNew is the top level node

records.each {
    items.add(new WhateverYouWant(it))
}
于 2013-07-26T20:09:12.607 回答