【问题标题】:XSLT transformation on client to avoid CORS with JavaScript客户端上的 XSLT 转换以避免 JavaScript 的 CORS
【发布时间】:2021-11-10 16:03:33
【问题描述】:

我有一个文本区域,我在其中粘贴一个 XML 文件并使用简单的 JavaScript 将其转换为 JSON。 我想用 XSLT 修改客户端上的 XHTML 并生成一个将转换为 JSON 的新 XML。 我总是收到 CORS 错误。

我的代码是:

<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);
} 

我应该在 xhr.open("GET",url,false); 的 url 中放置什么路径获取xml代码? xsl 代码可以硬编码,因为我只是删除了标签的前缀。

如何将新的xml导出为JSON.parse()呢?

【问题讨论】:

    标签: javascript xml xslt


    【解决方案1】:

    如果您将 XML 和/或 XSLT 数据作为字符串,则使用 DOMParser 解析它们,例如

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

    然后将该xslStylesheet 文档传递给XSLTProcessorimportStylesheet 方法。不需要使用XMLHttpRequest

    对 XML 文档执行相同的操作,例如

    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');
    

    【讨论】:

    猜你喜欢
    • 2018-10-26
    • 1970-01-01
    • 2011-12-25
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2015-03-02
    • 2015-12-03
    相关资源
    最近更新 更多