I had to wrap this in a command processor call to work. Otherwise you get exception Must not change document outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor
For me this also not works, 1 time I get similar error, second time it is added to structure, but not to file
Thank you, this works.