Why would you write code for that? It’s just a few lines of XSLT!
I just tried "Give me options for converting XML to JSON" and XSLT was 5th out of the 6 it gave me:
https://chat.openai.com/share/85aa3e93-f557-426c-b0ce-f3bce7...
I'm not sure how fun it is to work with in practice, given that the XML representation is quite verbose.