Tengo un área de texto donde pego un archivo XML y lo convierto a JSON con JavaScript simple. Quiero modificar el XHTML en el cliente con XSLT y producir un nuevo XML que se convertirá a JSON. Recibo errores CORS todo el tiempo.
mi código es:
<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); }qué ruta debo colocar en la url de xhr.open("GET",url,false); para obtener el código xml? El código xsl puede codificarse de forma rígida porque solo elimino un prefijo de las etiquetas.
¿Cómo puedo exportar el nuevo xml para JSON.parse()?
Si tiene los datos XML y/o XSLT como una cadena, use DOMParser para analizarlos, por ejemplo
xslStylesheet = new DOMParser().parseFromString(yourXSLTString, 'application/xml'); luego pase ese documento xslStylesheet al método importStylesheet del XSLTProcessor . No hay necesidad de usar XMLHttpRequest .
Haga lo mismo para el documento XML, por ejemplo
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');