无法使用Highlight.js以正确的顺序呈现XML

问题描述 投票:0回答:1

我正在尝试使用Highlight.js突出显示XML。

这里是示例codepen link

但是我面临两个问题:

  1. 自闭元素被呈现为非自闭标签,在上面的示例中是author元素。
  2. XML编码属性也未呈现。

我已经尝试实现将/>替换为/>的转义方法,但是它无法按预期方式工作。

示例:期望的XML

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

实际XML

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

是否有纠正此行为的方法。

javascript html underscore.js highlightjs
1个回答
1
投票

在这种情况下,code标签被解析为HTML。为了避免您可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.