IdeaModule retains previous libraries despite attempts to deliberately delete them

I had a problem which I posted on Stack Overflow:

Basically I’m finding that Gradle doesn’t replace the libraries with its own dependencies even when I try to force it to. That’s fine, maybe it’s by design. I mean, there is a way to work around it, right? It looks something like this:

idea {
  module {
    iml {
      beforeMerged { module ->

But even with this workaround, the .iml files still have library entries that were previously present.

I guess now I will be doing another workaround-for-a-workaround where I delete the nodes manually?

I guess what makes this difficult to workaround is that it isn’t clear from the docs how I can manipulate the XML nodes before merging.

Before merging, I get passed a org.gradle.plugins.ide.idea.model.Module and can’t see how I can get a node from that. I see other projects where they have used “module.node”, but that fails here.

And of course, withXml gets called after merging, so if I implement it in there, I will have to somehow figure out which libraries are legit and which ones are not.