javascripthtmlunderscore.jshighlightjs

Unable to render XML in correct order using highlight.js


I am trying to highlight the XML using highlight.js.

Here is the example codepen link

But I am facing two problems:

  1. the self closing elements are rendered as non-self closing tag, author element in above example.
  2. XML encoding attribute is also not getting rendered.

I have tried implementing escape method for replacing "/>" with /> but it is not working in expected way.

Example : Expected XML

<?xml version="1.0"?>
<catalog>
  <book id="bk112">
     <author id="1"/>
     <title>Visual Studio 7: A Comprehensive Guide</title>         
  </book>
</catalog>

Actual XML

  <catalog>
   <book id="bk112">
     <author id="1">
     <title>Visual Studio 7: A Comprehensive Guide</title>       
    </author>
   </book>
  </catalog>

Is there a way to correct this behaviour.


Solution

  • In this case, code tag gets parsed the HTML. to avoid you can use textarea

    (function() {
      var el = document.querySelector(".xml"),
        pre = document.querySelector("pre");
    
      pre.innerText = el.value;
      hljs.highlightBlock(pre);
    })();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/vs.min.css" rel="stylesheet"/>
    
    <div hidden>
      <textarea class="xml">
        <?xml version="1.0"?>
        <catalog>
          <book id="bk112">
             <author id="1"/>
             <title>Visual Studio 7: A Comprehensive Guide</title>
    
          </book>
        </catalog>
      </textarea>
    </div>
    
    <pre></pre>