The immediate problem is that you got the arguments to InserAfter
mixed up. First one should be the node to insert and the second one should be the reference node. The root element has no children yet, so LastChild
is going to be null
and hence the exeption. Using null
as a reference point is valid, but not as a node to add.
There are other issues but you said you are able to fix those, so there you go.