【问题标题】:XMLUnit-2 ignore certain nested XML elementsXMLUnit-2 忽略某些嵌套的 XML 元素
【发布时间】:2020-07-23 03:33:51
【问题描述】:

我的 XML 有点复杂,我必须从比较中忽略某些 entry,我该如何实现它?

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE ResourceObject PUBLIC "my_corp.dtd" "my_corp.dtd">
<ResourceObject displayName="TESTNGAD\AggUserFSP test" identity="CN=AggUserFSP test,OU=FSPAggeFrame,OU=unittests,DC=TestNGAD,DC=local" objectType="account" uuid="{97182a65-61f2-443c-b0fa-477d0821d8c4}">
   <Attributes>
     <Map>
       <entry key="accountFlags">
         <value>
           <List>
             <String>Normal User Account</String>
             <String>Password Cannot Expire</String>
           </List>
         </value>
       </entry>
       <entry key="homePhone" value="6555"/>
       <entry key="l" value="Pune"/>
       <entry key="memberOf">
         <value>
           <List>
             <String>CN=FSPGRP2,OU=ADAggF,OU=unittests2,DC=AUTODOMAIN,DC=LOCAL</String>
             <String>CN=FSPGRP1,OU=ADAggF,OU=unittests2,DC=AUTODOMAIN,DC=LOCAL</String>
             <String>CN=LocalAggFrame,OU=FSPAggeFrame,OU=unittests,DC=TestNGAD,DC=local</String>
           </List>
         </value>
       </entry>
       <entry key="objectClass">
         <value>
           <List>
             <String>top</String>
             <String>person</String>
             <String>organizationalPerson</String>
             <String>user</String>
           </List>
         </value>
       </entry>
       <entry key="sn" value="test"/>
       <entry key="st" value="MH"/>
       <entry key="streetAddress" value="SB ROAD"/>
       <entry key="title" value="QA"/>
       <entry key="userPrincipalName" value="AggUserFSP test@TestNGAD.local"/>
     </Map>
   </Attributes>
 </ResourceObject>

我试过了

Diff diff = DiffBuilder
             .compare(control)
             .withTest(test)
             .checkForSimilar().checkForIdentical()
             .normalizeWhitespace()
             .ignoreComments()
             .ignoreWhitespace()
             .withNodeFilter(node -> !(node.getNodeName().equals("accountFlags") ||
                            node.getNodeName().equals("homePhone"))).build();

但是,它不起作用。我应该如何在这里忽略一些XML entry

【问题讨论】:

    标签: java xml xmlunit xmlunit-2


    【解决方案1】:

    “accountFlags”和“homePhone”都不是元素名称,所以我的过滤器不会匹配任何内容。

    NodeFilter 必须返回 true,除非满足以下所有条件

    • 节点实际上是一个元素
    • 节点有一个名为“key”的属性
    • 此属性的值是“accountFralgs”或“homePhone”
        private boolean filter(final Node n) {
            if (n instanceof Element) {
                final String attrValue = ((Element) n).getAttibute("key");
                // attrValue is th eempty string if the attribute is missing
                return !("accountFlags".equals(attrValue) || "homePhone".equals(attrValue));
            }
            return true;
        }
    

    【讨论】: