开发者

Decode HTML encoded content using XSLT

开发者 https://www.devze.com 2023-04-11 04:44 出处:网络
I have a web page which executes some javascript upon a link click. The link is: <a href=\"javascript:void(0)\"

I have a web page which executes some javascript upon a link click. The link is:

<a
  href="javascript:void(0)"
  onclick="XsltTransform('category.xml','category.xslt');">Latest news</a>

The javascript is:

<script type="text/javascript">
  function XsltTransform(xmlfile, xslfile) {
  var xml = document.implementation.createDocument("", "", null);
  var xslt = document.implementation.createDocument("", "", null);

  xml.async = false;
  xslt.async = false;

  xml.load(xmlfile);
  xslt.load(xslfile);

  var processor = new XSLTProcessor();
  processor.importStylesheet(xslt);

  var XmlDom = processor.transformToDocument(xml)

  var serializer = new XMLSerializer();
  var output = serializer.seriali开发者_如何学PythonzeToString(XmlDom.documentElement);

  var outputDiv = document.getElementById("contentbody");
  outputDiv.innerHTML = output;
  }
</script>

The XML which is processed looks very much like:

<Content>
 <Body>&lt;p&gt;It may have taken over 12 years</Body>
</Content>

And the XSL which processes it is a simple xsl:value-of statement:

  <xsl:template match="/">
    <p>
      <xsl:value-of select="*/*/Body" disable-output-escaping="yes" />
    </p>
  </xsl:template>

The problem is that no matter what value I use in the 'disable-output-escaping' attribute of the 'value-of', I always get this rendered (as seen in Firefox web developer generated source view):

&lt;p&gt;It may have taken over 12 years

I would like the block of decoded HTML to become encoded when rendering and I was under the impression that this is what the disable-output-escaping would allow.

How do I get this very raw XML to become real HTML again?


Not all XSLT processors support disable-output-escaping. Firefox is one of them that does not.

There is an open bug for Firefox and it's lack of support for it: Bug 98168 - (doe) not working


Had a similar problem transforming ATOM XML where the content of the posts contained escaped HTML tags. disable-output-escaping seems to work in most browsers but not Firefox. So as a work around, in my XSLT I added the class="renderhtml" attribute to all problematic output nodes, as a hint to javascript. Then added the following code after the transform.

// work around for XSLT disable-output-escaping="yes" not working in Firefox
if (navigator.userAgent.indexOf("Firefox")!=-1) {
  // get all "renderhtml" hints (HTML escaped within CDATA/text) nodes, then unescape and render HTML code
  var nodes = document.getElementsByClassName("renderhtml");
  for (var i = nodes.length - 1; i >= 0; i--) {
    nodes[i].innerHTML = nodes[i].textContent;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号