Home > other >  XSLT transformation on client to avoid CORS with JavaScript
XSLT transformation on client to avoid CORS with JavaScript

Time:09-16

I have a textarea where I paste an XML file and convert it to JSON with simple JavaScript. I want to modify the XHTML on the client with XSLT and produce a new XML that will be converted to JSON. I get CORS errors all the time.

My code is:

<textarea id="xmltext" name="xmltext"></textarea>
<button onclick="xml2xslt()">transform</button>    


function xml2xslt(){
  var xslStylesheet;
  var xsltProcessor = new XSLTProcessor();
  var myDOM;
  var xmlDoc;

  var xhr = new XMLHttpRequest();
  xhr.open("GET", "<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"><html><body><h2>My CD Collection</h2><table border="1"><tr bgcolor="#9acd32"><th>Title</th><th>Artist</th></tr><xsl:for-each select="catalog/cd"><tr><td><xsl:value-of select="title"/></td><td><xsl:value-of select="artist"/></td></tr></xsl:for-each></table></body></html></xsl:template></xsl:stylesheet>", false);

  xhr.overrideMimeType("text/xml")
  xhr.send(null);

  xslStylesheet = xhr.responseXML;
  xsltProcessor.importStylesheet(xslStylesheet);

  // load the xml file
  xhr = new XMLHttpRequest();
  xhr.open("GET", "<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?><catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><country>USA</country><company>Columbia</company><price>10.90</price><year>1985</year></cd></catalog>", false);
  xhr.overrideMimeType("text/xml")
  xhr.send(null);

  xmlDoc = xhr.responseXML;
  var fragment = xsltProcessor.transformToFragment(xmlDoc, document);
  document.getElementById("xmltext").textContent = "";
  myDOM = fragment;
  document.getElementById("xmltext").appendChild(fragment);
} 

what path should I place in url of xhr.open("GET",url,false); to get the xml code? xsl code can be hard coded because I just remove a prefix of the tags.

How can I export the new xml so as to JSON.parse() it?

CodePudding user response:

If you have the XML and/or XSLT data as a string then use DOMParser to parse them e.g.

 xslStylesheet = new DOMParser().parseFromString(yourXSLTString, 'application/xml');

then pass that xslStylesheet document to the importStylesheet method of the XSLTProcessor. There is no need for using XMLHttpRequest.

Do the same for the XML document e.g.

xmlDoc = new DOMParser().parseFromString(`<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?><catalog><cd><title>Empire Burlesque</title><artist>Bob Dylan</artist><country>USA</country><company>Columbia</company><price>10.90</price><year>1985</year></cd></catalog>`, 'application/xml');
  • Related