Wednesday, October 15, 2014

XML Diff in PowerShell

Microsoft released a tool over a decade ago that is proving quite useful in my current work with loads of XML.

The tool can be loaded in PowerShell using Add-Type then used quite simply.  Below are some very simple examples.  There are more sophisticated ways to use the tool but for now I’m just showing how to do simple comparisons resulting in TRUE or FALSE.

This is proving very useful for diffing FIM Synchronization configuration files, which have megabytes of interesting detail in XML.

 

### Get it here: http://msdn.microsoft.com/en-us/library/aa302294.aspx

Add-Type -Path xmldiffpatch.dll

 

### Create the XmlDiff object

$xmlDiff = New-Object Microsoft.XmlDiffPatch.XmlDiff

 

### Simple compare: expect TRUE

$xmlDiff.Compare([xml]'<foo/>', [xml]'<foo/>')

 

### Same content, different format: expect TRUE

$xmlDiff.Compare([xml]'<foo/>', [xml]'<foo></foo>')

 

### Simple compare: expect FALSE

$xmlDiff.Compare([xml]'<foo/>', [xml]'<bar/>')

 

### Ordering is ignored on attributes: expect TRUE

$xmlDiff.Compare([xml]"<foo a='1' b='2' c='3'/>", [xml]"<foo c='3' b='2' a='1'/>")

 

### Ording is NOT ignored on children: expect TRUE

$xmlDiff.Compare([xml]"<foo><a/><b/><c/></foo>", [xml]"<foo><c/><b/><a/></foo>")

 

### Oh just ignore the children order: expect FALSE

$xmlDiff = New-Object Microsoft.XmlDiffPatch.XmlDiff([Microsoft.XmlDiffPatch.XmlDiffOptions]::IgnoreChildOrder)

$xmlDiff.Compare([xml]"<foo><a/><b/><c/></foo>", [xml]"<foo><c/><b/><a/></foo>")

 

 

No comments: