The following is my attempt to do that. It is written as a function and should be revised. The code structure is not so elegant and it could not be so optimised for CPU and memory usage:
I realised that a common convention for writing musical notation should precede musicXML export while doing this attempt.