There was an issue though, it transpires I do need to preserve the attributes. The standard way to do this would probably be to make the attributes children of the current node and add a '#text' child to capture the original text value.
So for example the following xml...
<root> <item> <title>Porro est qui</title> <link>http://boom.shakalack</link> <author id="123">Jasmine Smith</author> </item> </root>
would produce something like this...
{ "root":{ "item":{ "title":"Porro est qui", "link":"http://boom.shakalack", "author": { "#text":"Jasmine Smith", "-id":"123" } } } }
or this...
{ "root":{ "item":{ "title":"Porro est qui", "link":"http://boom.shakalack", "author": { "#text":"Jasmine Smith", "@attributes":{ "id":"123" } } } } }
This kind of formatting is not going to work for me though, the fact that if an attribute is added to a xml node which didn't have one before, your json format will change makes this too risky to use. Also the issue that on some nodes you can use the value directly and on others you need to go down a level to find the child '#text' node, make this a rather messy solution.
After thinking about it I settled on a, not ideal, but fairly simple solution, appending the attribute to the current named node at the same level, so given the same xml the output becomes....
{ "root":{ "item":{ "title":"Porro est qui", "link":"http://boom.shakalack", "author":"Jasmine Smith", "author@id":"123" } } }
This format you can now access these attributes, for example in a mustache template you might use the following...
{{#item}} <details> <summary>{{title}}</summary> <div><a href="/authors/{{author@id}}/show">{{author}}</a></div> </details> {{/item}}
This works quite well for me, it's simple and easy to read. One has to keep in mind that the presence of an @ symbol means you can't use dot notation though, e.g. item.author@id will not work you have to do this item["author@id"] instead, as I mentioned, not ideal!
view the xml to json javascript on github
Simple XML to JSON