Update add by xpath. Fix a potential stackoverflow error

Update add by xpath. Fix a potential stackoverflow error
Also fixed an error when adding elements.  It used to add to end of element even if that was the wrong place to add the elements.