0

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

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

$d.Compare("c:\scripts\ps\ref.xml", "c:\scripts\ps\tgt.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:\scripts\ps\ref.xml", "c:\scripts\ps\tgt.xml", $false)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException

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

有没有其他人见过这个?你是怎么解决的?

4

3 回答 3

1

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

# 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)\XmlDiffPatch\Bin\xmldiffpatch.dll"

$xmlD1=[XML](Get-Content 'd:\temp\M1.xml')
$xmlD2=[XML](Get-Content 'd:\temp\M2.xml')
$xmlWriter = [System.Xml.XmlWriter]::Create("d:\temp\M3.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();

两个相似或不同的 XML 文件的位置M1.xml和位置将收到增量。M2.xmlM3.xml

于 2015-04-28T06:00:24.323 回答
1

看起来 XMLDiffPatch 库的方法中有一个错误,它Microsoft.XmlDiffPatch.XmlDiff.NormalizeText(String text)无法处理纯空格字符串 ( " ")。如果您通过一个,该方法会尝试实例化一个string负长度,因此异常。

我正在比较的一些 XML 包含的属性如AttributeName=" ",当库试图对其进行规范化时,它们会导致这些异常。我浏览了XML 规范,并没有禁止这样的属性。

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

于 2020-02-21T15:12:57.853 回答
0

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

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

于 2021-02-23T12:56:47.887 回答