Skip to content

Instantly share code, notes, and snippets.

@lacan
Created April 6, 2021 07:58
Show Gist options
  • Save lacan/06fb3a7f11dd4fa549aadc5478f8083d to your computer and use it in GitHub Desktop.
Save lacan/06fb3a7f11dd4fa549aadc5478f8083d to your computer and use it in GitHub Desktop.
[Combine XML Files from NIS Elements Positions] Combines multiple positions lists into a single one #Groovy #NISElements #Nikon #XML #Fiji
#@ File xmlFolder (label="Folder with XML Files to combine", style="directory")
// List all XML Files
def files = xmlFolder.list({d, f-> f ==~ /.*.xml/ } as FilenameFilter).collect{ new File( xmlFolder, it) }
// Make a result folder
resultfolder = new File( xmlFolder, "combined")
resultfolder.mkdirs()
// Get the reference from which we will append the others to
def refXML = new XmlSlurper( false, false ).parse( files.pop() )
// Structure is xml > no_name_ > PointXXXXXX so we need to get all Nodes with Point in the String
// And we will need to rename them
// Get the max index of the points in list 1
def pmax = refXML.no_name."*".findAll{ it.name().contains("Point")}.collect{ it.name().substring(5) as int }.max()
// Append each file with a new position index for each Point
files.each{ file ->
// Read the file
def appendXML = new XmlSlurper( false, false ).parse( file )
// Rename the nodes in list 2
appendXML.no_name."*".findAll{ it.name().contains("Point") }.each{ point ->
point.replaceNode { node ->
def newname = sprintf('Point%05d', ++pmax)
"$newname"(node.attributes(), node.children())
}
}
// Append to reference list
appendXML.no_name."*".findAll{ it.name().contains("Point") }.each{ point ->
refXML.no_name.appendNode(point)
}
}
// Build the new XML. Need to explicitly set the header
def outputBuilder = new StreamingMarkupBuilder()
def resultXML = outputBuilder.bind{
mkp.yieldUnescaped '<?xml version="1.0" encoding="UTF-8"?>'
mkp.yield refXML // This line returns all the xml from file 1 which was modified
}
//resultXML.writeTo( new File( resultfolder, "Combined.xml" ).newWriter("UTF-8") )
new File( resultfolder, "Combined.xml" ).withWriter("UTF-8") {
it.write (XmlUtil.serialize( refXML ))
}
/**
* !!! Warning !!!
* Groovy's 'newWriter' method write an extra newline to the XML which was breaking NIS Elements.
* If you cannot load the file into NIS, check that it does not have trailing NewLines
*/
import groovy.xml.*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment