I explaned my attempt in the attachment. You can also try your solution on my created example in "Sample.xmls"