Groovy web console

subscribe to the feed Subscribe
to this
site

CSV to XML

Published 5 months ago by Bais with tags csv xml convert no libs
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
testo = '''
EXTRACT|2022-06-30|0||11
EXTRACT123|2022-06-30|0||11
456|2022-06-30|0||11|hhh|2022-06-30|0||11
''';

    def newbody = ""
    def maxCount = 0
    def myxml = "<xml>\r\n\t<root>\r\n"
    def delimeter = "|"
    def regexp_delimeter = /\|/

 println("Source csv")
 println(testo)

    testo.readLines().each {
        if (it.count(delimeter) > maxCount) {
            maxCount = it.count(delimeter)
           //println(maxCount)
        }
    }
    
    testo.readLines().each {
        empty = ''
        //print("String length:")
        //println(it.length())
        //println(it.count(delimeter))

        if (it.count("|") < maxCount && it.length() > 0){
            for (i = 0; i <= it.count(delimeter)+1; i++) {
                empty = empty + '|'
            }
            result = it+empty
            newbody = newbody+result+"\r\n"
        } else {
            newbody = newbody+it+"\r\n";
        }
    }

    
    newbody.readLines().each {

      //str = it.split(/\|/);
      str = it.split(regexp_delimeter );
      Integer i = 0;   
      row = "";
      //println(str);
      myxml = myxml + "\t\t<row>\r\n";

      for( String values : str ) {
             //println(values);
             i = i+1;
             fieldopen = "\t\t\t<FIELD" + i.toString() +">";
             fieldclose = "</FIELD" + i.toString() +">\r\n";
             row = fieldopen + values +fieldclose;
             myxml = myxml + row;
             //println(row)
      }
     myxml = myxml + "\t\t</row>\r\n";
    //println(myxml);
    }
myxml = myxml + "\t</root>\r\n</xml>\r\n";
println("Result xml:")
println(myxml)