Stefano Locati

Programming Adventures (WIP)

Remove a dependency from pom.xml

I wrote another simple Groovy script to remove one or more dependencies from a pom.xml - Here is how to use it:

[sourcecode language="bash"]

$ pomRm rdbms


$ pomRm rdbms rm

org.datanucleus:datanucleus-rdbms:3.0.4 REMOVED


The first form just lists the matching artifacts, without changing the pom.xml, while adding 'rm' in the command line as second parameter, actually remove the dependency from the pom.xml

Here is the source code:

[sourcecode language="groovy"]


import groovy.xml.XmlUtil

def matchAndModify(String search, boolean remove) {

def pom = new XmlSlurper(false, false).parse('pom.xml')

String deleted = ''

pom.dependencies.dependency.each { dep ->

if (dep.groupId.text() =~ /${search}/ || dep.artifactId.text() =~ /${search}/) {

if (remove) {

dep.replaceNode { }

deleted = 'REMOVED'

} else {

deleted = ''


println "${dep.groupId}:${dep.artifactId}:${dep.version} ${deleted}"



return pom


boolean checkArgs() {

if (!(1..2).contains(args.size())) {

println 'pomRm: remove a dependency in Maven\'s pom.xml'

println "\nUsage: "

println 'with 1 argument, look for the string specified and print matching dependencies'

println 'with 2 arguments, look for the string specified and remove matching dependencies'

println "\nExample: pomRm datanucleus-core -> list the matching dependencies"

println 'Example: pomRm datanucleus rm -> actually remove all matching dependencies'

println 'More Examples: http://www.stefanolocati.it/blog/?p=1226'

return false;


return true;


String grabArgIfExists(int position) {

if (position < args.size()) {

return args[position]


return ''


if (checkArgs()) {

String search = grabArgIfExists(0)

boolean remove = grabArgIfExists(1) == 'rm'

def pom = matchAndModify(search, remove)

File file = new File('pom.xml')

file.write XmlUtil.serialize(pom)