1

How to save string to file to specify place ? I use path << 'string' to save, but it give it on end of file. In destination to xml(path) file have </databaseChangeLog>. I want to save to file before that word occurs.

There is java solution click, but it is static line. My file will be dynamic, I don't know with line it will be.

def add_to_version() {
   def path = new File('C:/groovy/version-1.xml')       
   def branchId = "Promt"
   def lineCount = 0

  def count = path.eachLine { line ->        
    if(line.contains('<include file="' + branchId + '/' + branchId + '.xml" ')){
        wordCount++             
    }else if(lineCount == 1 ){
        println "package is there"
    }
 }
  if(lineCount == 0){
    path << '<include file="' + branchId + '/' + branchId + '.xml" ' + 'relativeToChangelogFile="true"/>'    
  }
} 

code above do that : xml1 and I want to get xml like that : enter image description here

John Doe
  • 147
  • 1
  • 1
  • 10
  • please modify your question and provide an example content of your file and what should be in it after modification. in general: you have to read full file in memory, change loaded data, and write it back to file. in groovy you can use xmlparser (or xmlslurper) to read and manipulate xml. – daggett Sep 27 '17 at 08:55
  • I add my xml file and what i want :) Looking in xmlparser... – John Doe Sep 27 '17 at 09:34

1 Answers1

2

you can use xml parser like this:

def add_to_version(String branchId) {
   def path = new File('C:/groovy/version-1.xml')       
   def xml = new XmlParser().parse(path)
   xml.appendNode("include", [
      file:"${branchId}/${branchId}.xml",
      relativeToChangelogFile:"true"
   ])
   groovy.xml.XmlUtil.serialize(xml, path.newOutputStream())
} 

this variant will not keep the xml formatting and comments

however xml will be valid

daggett
  • 26,404
  • 3
  • 40
  • 56