2010-09-16 57 views
1

將XML文檔與XMLUnit進行比較時,是否可以忽略元素中的一些子元素?我想在比較元素時忽略元素中的所有空白文本節點。將XML文檔與XMLUnit進行比較時忽略少數兒童

最好的問候, 凱沙夫

+0

1)覆蓋differenceFound在DifferenceListener但隨後它忽略了元素中的其他差異。 2)設置XMLUnit.setIgnoreWhitespace(true)。這似乎不適用於compareXML(文檔控制,文檔測試) – keshav84 2010-09-17 05:25:45

+0

請參閱http://stackoverflow.com/questions/1241593/java-how-do-i-ignore-certain-elements-when-comparing-xml – 2011-05-13 21:35:00

回答

1

你可以使用這個監聽器:

import org.custommonkey.xmlunit.Difference; 
import org.custommonkey.xmlunit.DifferenceConstants; 
import org.custommonkey.xmlunit.DifferenceListener; 
import org.w3c.dom.Node; 

import java.util.HashSet; 
import java.util.Set; 

public class IgnoreChildrenOfNamedElementsDifferenceListener implements DifferenceListener { 
    public IgnoreChildrenOfNamedElementsDifferenceListener() {} 

    public int differenceFound(Difference difference) { 
     if (difference.getId() == DifferenceConstants.HAS_CHILD_NODES_ID || 
       difference.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID || 
       difference.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) { 
       return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; 
      } 
     }  
     return DifferenceListener.RETURN_ACCEPT_DIFFERENCE; 
    } 

    @Override 
    public void skippedComparison(Node control, Node test) {} 
} 

然後你可以在下面的方式來使用它:

Diff diff = new Diff(expectedDoc, obtainedDoc); 
diff.overrideDifferenceListener(new IgnoreChildrenOfNamedElementsDifferenceListener("TestDateTime"));