/** * parseAndRemove.groovy * * @author joerg.feuerhake[at]free-penguin.org * 09/21/2005 **/ //import a whole lot of java packages import java.io.FileOutputStream; import java.io.File; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * This script takes two arguments. The sourcefile to read from * and the targetfile to write to. * * It parses file specified in argument one, removes all child * branches under nodes named like argument three and writes the * result to the file named in argument two. The script ignores * further arguments. **/ //check arguments if(args.size() < 3){ println "TOO FEW ARGUMENTS" println "The script takes three arguments." println "The sourcefile to read from and" println "the targetfile to write to and" println "the tagname of the nodes, where" println "child branches shall be deleted." println " " println "EXAMPLE: groovy parseAndRemove.groovy myFile.xml myNewFile.xml mynodename" } else{ dothis(this.args[0], this.args[1], this.args[2]) println("DONE"); } //hope for the best def dothis(infile, outfile, nodename) { //read a file to a xml document DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance() DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder() Document doc = docBuilder.parse(new File(infile)) doc.getDocumentElement().normalize() //list all nodes named 'state' NodeList StateNodes = doc.getElementsByTagName(nodename); StateNodes.each(){ Node StateNode = (Node)it; //remove child node if exists while(StateNode.hasChildNodes()){ println("remove::"+StateNode.getFirstChild()); StateNode.removeChild(StateNode.getFirstChild()); }; }; //write changed doc to a new file TransformerFactory tFactory= TransformerFactory.newInstance(); Transformer transformer= tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new FileOutputStream(outfile)); transformer.transform(source,result); }