這很簡單。 Here is an exmple。
樣本HTML:
<p><a href="#" data-xpath="/bib/book[2]">2nd book</a></p>
<p><a href="#" data-xpath="/bib/book[3]/author[1]">1st author of the 3rd book</a></p>
<p><a href="#" data-xpath="/bib/book/author">All authors</a></p>
<div id="doc-content"></div>
樣品CSS:
#doc-content { white-space: pre; }
.highlight { color: red; }
和JavaScript代碼。示例XML文檔:
var doc = `<bib xmlns="">
<book>
<title>TCP/IP Illustrated</title>
<author>Stevens</author>
<publisher>Addison-Wesley</publisher>
</book>
<book>
<title>Advanced Programming in the Unix Environment</title>
<author>Stevens</author>
<publisher>Addison-Wesley</publisher>
</book>
<book>
<title>Data on the Web</title>
<author>Abiteboul</author>
<author>Buneman</author>
<author>Suciu</author>
</book>
</bib>`;
一些效用函數來生成的GUID:
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
主要功能得到XPath表達式從數據的xpath屬性,發現由表達式匹配的節點與之前和之後插入魔術註釋匹配節點。然後XML文檔被串行化爲一個字符串。而在最後,我們通過<跨度類=「亮點」替換魔術註釋>:
var parser = new DOMParser();
var printer = new XMLSerializer();
function highlightXPath(e) {
var xpath = e.target.dataset.xpath;
var xml = parser.parseFromString(doc, 'text/xml');
var nodes = xml.evaluate(xpath, xml, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var id = guid();
for (var i = 0; i < nodes.snapshotLength; i++) {
var node = nodes.snapshotItem(i);
node.parentNode.insertBefore(xml.createComment('start_' + (i+1) + '_' + id), node);
node.parentNode.insertBefore(xml.createComment('end_' + (i+1) + '_' + id), node.nextSibling);
}
var str = printer.serializeToString(xml);
var content = document.getElementById('doc-content');
content.innerHTML = str.replace(/</g, '<')
.replace(/<!--start_(\d+)_.*?-->/g, '<span id="highlight$1" class="highlight">')
.replace(/<!--end_.*?-->/g, '</span>');
}
附加事件處理程序的鏈接並顯示XML文檔的初始未高亮顯示的內容:
window.onload = function() {
var links = document.querySelectorAll('a[data-xpath]');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', highlightXPath);
}
var content = document.getElementById('doc-content');
content.innerHTML = doc.replace(/</g, '<');
};
Dimitre Novatchev實現HTTP ://www.huttar.net/dimitre/XPV/TopXML-XPV.html。 –
謝謝!這個實現對我來說太複雜了。看來他使用XSLT等我有一個更簡單的解決方案。 – Denis