XmlDiffPatch 引发异常长度不能小于零



我正在PowerShell中构建一个比较引擎脚本,我需要能够比较的一件事是XML文件。当我使用本机PowerShell比较对象时,它返回0个差异,但是如果我抓住外部xml(文本表示)和差异,我确实会得到差异。不幸的是,这会将所有内容放入一个长字符串中,因此没有用。

然后,我尝试使用Microsoft中的 XmlDiffPatch 库,但是如果我使用 PowerShell 中的示例程序或库,我的 2 个 XML 文件会失败并出现异常:

$d.Compare("c:scriptspsref.xml", "c:scriptspstgt.xml", $false)
Exception calling "Compare" with "3" argument(s): "Length cannot be less than zero.
Parameter name: length"
At line:1 char:1
+ $d.Compare("c:scriptspsref.xml", "c:scriptspstgt.xml", $false)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException

无法访问此库的源代码,除了错误之外,我不知道发生了什么。2 XML在IE中的解析很好,所以我知道它们是有效的XML。

以前有其他人见过吗?你是怎么解决的?

这是我使用它的一种方式,也是想要发现它的人的完整示例:

# Test-xmldiffpatch.ps1
# This code need to download Microsoft tool
# https://msdn.microsoft.com/en-us/library/aa302294
# or Nuget
# https://www.nuget.org/packages/XMLDiffPatch/
# Load the external DLL
Add-Type -Path "C:Program Files (x86)XmlDiffPatchBinxmldiffpatch.dll"
$xmlD1=[XML](Get-Content 'd:tempM1.xml')
$xmlD2=[XML](Get-Content 'd:tempM2.xml')
$xmlWriter = [System.Xml.XmlWriter]::Create("d:tempM3.xml")
$xmlDiff= New-Object Microsoft.XmlDiffPatch.XmlDiff
$xmlDiff.IgnorePrefixes=$true
$xmlDiff.IgnoreChildOrder=$true
$xmlDiff.IgnoreNamespaces=$true
$blIdentical = $xmldiff.Compare($xmlD1, $xmlD2, $xmlWriter);
$blIdentical
$xmlWriter.Close();

其中M1.xmlM2.xml是两个相似或不同的 XML 文件M3.xml将接收增量。

看起来XMLDiffPatch库的方法Microsoft.XmlDiffPatch.XmlDiff.NormalizeText(String text)中有一个错误,它不能处理仅空格的字符串(" ")。如果传递一个,该方法将尝试实例化负长度的string,因此会出现异常。

我正在比较的一些XML包含AttributeName=" "等属性,当库尝试规范化它们时,它们会导致这些异常。我浏览了 XML 规范,这样的属性是不是被禁止的。

事实证明它无法修复,并且没有好的解决方法(除了在比较之前"修复"XML)。我最终改用 XmlUnit.Net 库。

对于遇到这个(像我一样)XmlDiffPatch源代码的人以及此问题的修复程序,可在此处获得: - https://github.com/shadolight/XmlDiffPatch

不是我的回购只是在寻找相同的解决方案。

> 2022+ 中使用的软件包:https://www.nuget.org/packages/LovettSoftware.XmlDiff
与现代.NET版本兼容(NETStandard2.0,NET6+,甚至.NET 4.5.2)

它来自官方Microsoft Xml记事本存储库

最新更新