The pope gives you two years to withdraw your troops. If you occupy the province and assault the castle before the the two year limit it up, you'll be OK.
Another way is to attack another Catholic faction. In your case let's say the Danes. You'll get warned by the pope, so you withdraw you troops from Denmark. Now you can attack any other Catholic faction without risking excommunication.