[1] Line #21
[2] Lines #23-32
The loop j may be better used by reversing order of the index and coupled it with "break" for the first match. But this is only a detail you have to consider rewriting everywhere.
[3] The main error asked. It is an misunderstanding of appendChild(). Line #48
[4] On the whole, the code does not give enough credit to
java's DOM model. If you use DOM to flatten the xml tree using getChildNodes(), it is far away to use the more pertinent method getElementsByTagName() on the child Element everywhere. For instance, line #35
The coding inside would have to be rewritten. It would be greatly simplified and more focused.., eliminating a lot of checking...