views:

39

answers:

1

I have the following xml

<AAA>
  <BBB>Total</BBB>
</AAA>

Transforming it with the following xslt using the xsl:copy-of tag, because I want to use the xml to create a xml doc in js.

<xsl:template match="/">
  <![CDATA[
    function myFunc() {
      xmlStr = ']]><xsl:copy-of select="/"/><![CDATA[';
    }
  ]]>
</xsl:template>

The output looks like this

    function myFunc() {
      xmlStr = '<AAA>
  <BBB>Total</BBB>
</AAA>';
    }

JS doesn't like this because of the missing semicolons ending the lines. How can I fix my xsl to get the below result:

function myFunc() {
  xmlStr = '<AAA><BBB>Total</BBB></AAA>';
}

I've tried normalize-space() and translate() but they strip the tags from the xml.

Thanks!

+1  A: 

Use the xsl:strip-space element:

<xsl:strip-space elements="AAA"/>
<xsl:template match="/">
<![CDATA[
  function myFunc() {
    xmlStr = ']]><xsl:copy-of select="AAA"/><![CDATA[';
  }
]]>
</xsl:template>

It will remove all of the whitespace from the element AAA before copying it. You have to watch out, though, because it will remove any internal spacing from text nodes under AAA as well, so it's kind of overkill. If you have some elements where space needs to be preserved, list them as exceptions in an xsl:preserve-space element. But judging from your example I don't think that will be a concern.

Welbog
@davomarti: Be sure that your XML can never contain any single quotes, or your JavaScript will break. Especially, make sure your XML does not contain user-generated data, since this approach carries a high XSS risk. Best is to request the XML separately from the server via AJAX, instead of directly injecting it into your JS code.
Tomalak
Thanks Welbog,That's what I was looking for. Tomalak,That makes alot of sense, but I'm working inside a framework and the best I can do is get the xml through xsl.
@davomarti - Hint: If the answer solved your problem, you should mark it as accepted.
Tomalak