Hey there,
I have done similar jobs in the past.
Do you need all of this to be handled in a bash script, or are you able to use some external script handler like python or something like that?
It can be done with a bash script and some small other applications like xmllint, but if using something like python is not an issue, it would make things a lot easier, and also simpler for you to maintain it in the future.
Best regards.