for each node there is easy way to get it's xpath: either by storing it as array/list while #2, or via function which goes recursively up until parent is null, then reverses array/list of encountered nodes.
something like that.
UPD:
and concatenate final list in order to get final xpath.
don't think attributes will be a problem.