views:

348

answers:

2

Hello,

I would like to copy XML using XSLT into JSON.

The JSON result would look like this:

 callback( {"xml":"
 <?xml version="1.0" encoding="UTF-8"?>
 <root>
 ...
 </root>
 "})

and my XSLT so far:

 <xsl:template match="/">
   <xsl:text>callback( {"xml":"</xsl:text>
    <xsl:copy-of  select="*"/>
   <xsl:text>"} )</xsl:text>
 </xsl:template>

Anyone has an idea what else, besides quotes, I have to replace and how to replace? I would like to load and parse the XML file in Javascript?

Thanks a lot,
Ralph

+1  A: 

This task is far easier accomplished using JavaScript instead of XSLT only because the ending grammar is not XML affiliated, and because it is unlikely you are transforming anything beyond mere syntax.

You are only transforming the syntax and nothing affiliated with the data then it is a syntax only translation. This is not what XSLT was designed for. Every XML technology shares a common syntax, so syntax translations are a non-issue when shaping data from one XML grammar to another. Additionally this is a simple task.

What you need is the following: A string literal that represents your JS code of an array or object literal index prior to the data element, the data element using the innerHTML of the document.getElementsByTagName array, and then bit of JS to finish the array or object literal index code. Use a loop to go through each element from the XML and build it into a string literal that represents the necessary JS code to build each index of your JSON object. Then once complete stick the appropriate beginning and end on what is dynamically created to finish the syntax. This should be a very quick process.

I think there is no other choice. The response of a REST request is xml but I need the response in json. So first I wrote XSLT with transforms only a few elements into json but I think it would be easier to copy the whole xml into json just as one object.Then I could load the xml into javascript and parse it.
Ralph Kretzler
Perhaps I was not clear. I edited my post to be more specific.
A: 

You could use the open source xml2json XSLT code. You can also write it on your own if you feel that what the current code does is inadequate. From what I have seen, I think that the code in the below project doesnt support attributes(if you can define how they should appear in your json).

http://code.google.com/p/xml2json-xslt/
Thiyagaraj
I looked into this project and it transforms xml into json but then I had to transform the json objects back to xml. So I thought it is easier to copy the whole xml element into json. Back in the client (browser) I could then parse the xml element with xpath.
Ralph Kretzler