【问题标题】:Are there any tools that can compare HTML documents by DOM structure?是否有任何工具可以通过 DOM 结构比较 HTML 文档?
【发布时间】:2010-09-21 13:53:02
【问题描述】:

我想比较两个 HTML 文档,并想知道它们是否相同。但只按DOM结构比较,即忽略标签中属性的顺序,例如<table id="one" name="table"><table name="table" id="one">是一样的。

【问题讨论】:

标签: javascript xhtml


【解决方案1】:

DOM Level 3 Core 提供了 isEqualNode() 方法,它比较内容给出解析后的 DOM 节点。

Firefox、Chrome、Safari 和 IE9 支持此功能,但 Opera 或更早版本的浏览器不支持。如果您需要其他浏览器的支持,则必须自己实现。这是 JS 中的部分实现:

function Node_isEqualNode(that, other) {
    // Use native support where available
    //
    if ('isEqualNode' in that)
        return that.isEqualNode(other);

    // Check general node properties match
    //
    var props= ['nodeType', 'nodeName', 'localName', 'namespaceURI', 'prefix', 'nodeValue'];
    for (var i= props.length; i-->0;)
        if (that[props[i]]!==other[props[i]])
            return false;

    // Check element attributes match
    //
    if (that.nodeType===1) {
        if (that.attributes.length!==other.attributes.length)
            return false;
        for (var i= that.attributes.length; i-->0;)
            if (!Node_isEqualNode(that.attributes[i], other.getAttribute(that.attributes[i].name)))
                return false;
    }

    // Check children match, recursively
    //
    if (that.childNodes.length!==other.childNodes.length)
        return false;
    for (var i= that.childNodes.length; i-->0;)
        if (!Node_isEqualNode(that.childNodes[i], other.childNodes[i]))
            return false;
    return true;
}

请注意,这不会对 DOM Level 3 Core 要求的额外 DocumentType 属性进行测试。你可以很容易地添加它,但是浏览器对 entities 之类的东西的支持还是很弱的。

【讨论】:

    【解决方案2】:

    我遇到了这个问题,并且能够通过使用 jQuery 的 .html() 函数将我的 html 代码放入 div 然后再次将其取出来解决它,从而获得代码的规范表示。至少在 Firefox 4 和 IE8 中似乎可以正常工作。

    function compareHtml(a, b) {
        var div = $(document.createElement('div'));
        div.html(a);
        var aNormalized = div.html()
        div.html(b);
        var bNormalized = div.html()
        return aNormalized == bNormalized;
    }
    

    【讨论】:

      【解决方案3】:

      如果需要比较静态内容可以试试diffxmlxmldiff(后者也支持html文件。

      【讨论】:

        【解决方案4】:

        我已经使用WinMerge 很长时间了,我从来没有遇到过任何问题。

        我将它用于 php/html/css 等 - 但我的同事也将它用于 delphi、c# 等。

        【讨论】:

          【解决方案5】:

          我已经解决了问题,daisydiff 是一个解决方案

          【讨论】:

          • DaisyDiff 给出了一些空指针。请分享您的解决方案。
          猜你喜欢
          • 2010-09-08
          • 2011-06-25
          • 2013-05-14
          • 2017-04-11
          • 1970-01-01
          • 2013-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多