The real meat of this solution is the
addElementToParent method. What it does it searches for the parent element of the provided xpath. If it doesn't find the parent in the document it will create it via a recursive call. Another trick is it will create any siblings that are needed in case the parent has an index (like /root/parent[3]). Once all the prerequisite elements are created it will then create the element we originally asked for.
This example will create this XML even though we only really tell it to create 5 elements. (the elements depend on the
data element so it is created automatically.