Search code examples
c#xmldynamicxmlunit

How to make XMLUNIT's WithNodeFilter dynamic C#


I am working on an app which compares XML files. The user may input a list of nodes in which they want to exclude in the comparison. For my comparison I am using XMLUNIT. I need to dynamically add the user input.

The below code works, but is not dynamic to the user input:

private bool Example1(ISource control, ISource test)
{
    var excludedNodes = new List<string> { "UserInput1", "UserInput2", "UserInput3" };
    var diff = DiffBuilder
        .Compare(control)
        .WithTest(test)
        .WithNodeFilter(x => !(x.Name.Equals(excludedNodes[0]) || x.Name.Equals(excludedNodes[1]) || x.Name.Equals(excludedNodes[2])))
        .Build();
    var hasDifferences = diff.HasDifferences();
    return hasDifferences;
}

My attempt at dynamically creating the above:

private bool Example2(ISource control, ISource test)
{
    var excludedNodes = new List<string> { "UserInput1", "UserInput2", "UserInput3" };
    var diffBuilder = DiffBuilder
        .Compare(control)
        .WithTest(test);
    foreach (var excludedNode in excludedNodes)
    {
        diffBuilder.WithNodeFilter(x => !x.Name.Equals(excludedNode));
    }
    var diff = diffBuilder.Build();
    var hasDifferences = diff.HasDifferences();
    return hasDifferences;
}

It appears that chaining together "WithNodeFilter" like I did in example2 does not work.


Solution

  • I can't compile to be sure, but I think you need to think of it as checking if the excluded nodes has your node.Name - instead of checking the name and comparing it to each excluded node.

    private bool Example1(ISource control, ISource test)
    {
        var excludedNodes = new List<string> { "UserInput1", "UserInput2", "UserInput3" };
        var diff = DiffBuilder
            .Compare(control)
            .WithTest(test)
            .WithNodeFilter(x => !excludedNodes.contains(x.Name))
            .Build();
        var hasDifferences = diff.HasDifferences();
        return hasDifferences;
    }