2010-09-21 78 views
5

我想比较两个HTML文档,并且想知道它们是否相同。但是只能通过DOM结构进行比较,这意味着忽略标签中属性的顺序,例如,<table id="one" name="table">,<table name="table" id="one">是相同的。是否有任何工具可以通过DOM结构比较HTML文档?

+1

可能重复[是否有任何工具,有比较的2个网页结构?](http://stackoverflow.com/questions/48669/are-there-any-tools-out-there比较2-web-pages的结构) – 2010-09-21 14:04:47

+0

@DanielVandersluis不同意重复。另一个问题也想忽略实际的id和文本值。 – 2014-02-27 05:19:36

回答

1

,如果你需要比较静态的内容,你可以给diffxmlxmldiff一试(HTML文件以后也有支持。

+0

非常感谢,这很有用 – jason 2010-09-22 08:05:32

3

DOM Level 3的核心提供了比较内容给予解析DOM节点的方法isEqualNode()

这是由火狐,Chrome,Safari和IE9,但不是歌剧或更早版本的浏览器都支持。如果您需要在其他浏览器的支持,你将不得不自己实现它下面是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这样的浏览器支持是非常薄弱的​​。

0

我必须解决的问题,daisydiff是一个解决方案

+0

DaisyDiff给出了一些空指针。请分享您的解决方案。 – 2013-09-26 04:54:37

0

我用WinMerge了海拉很长一段时间,我从来没有任何问题了。

我使用它的PHP/HTML/CSS等 - 但我的同事也使用它的德尔福,C#和更多。

3

我有这个问题,并能够解决它通过使用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; 
} 
相关问题