比较PowerShell中的XML文件,同时忽略某些标记

时间:2016-09-06 13:35:46

标签: xml powershell

我正在使用PowerShell使用以下代码比较两个不同的xml文件

Compare-Object (Get-Content C:\Users\Desktop\newtask3.xml | Where-Object { $_.Trim() -ne '' })(Get-Content C:\Users\Desktop\newtask4.xml | Where-Object { $_.Trim() -ne '' })

比较以下两个xml文件。

<html>a
    <ID>GT-ANI-2016-05-02T21:01Z</ID>
    <CreationDate>2016-05-02T21:01:40</CreationDate>
    <Total> 5000 </Total>
    <type>ANI</type>
</html>

使用

<html>a
    <ID>GT-ANI-2016-05-03T21:06Z</ID>
    <CreationDate>2016-05-03T21:06:40</CreationDate>
    <Total> 5000 </Total>
    <type>ANI</type>
</html>

我的问题是,当comapring这两个xml文件时,如何确保PowerSchell脚本忽略其中的唯一字段。

2 个答案:

答案 0 :(得分:0)

据我所知,没有一种简单的方法可以做到这一点。您可以将xml文档作为变量导入,然后查找共享属性并过滤掉作为数组的属性。然后使用已过滤的属性列表进行比较。

[xml]$XmlDocument1 = Get-Content -Path C:\example1.xml
[xml]$XmlDocument2 = Get-Content -Path C:\example2.xml
$xml1props = ($XmlDocument1.html | gm | ? {$_.membertype -eq "Property"  -AND ($_.definition.split(" "))[0] -eq "string"}).name
$xml2props = ($XmlDocument2.html | gm | ? {$_.membertype -eq "Property"  -AND ($_.definition.split(" "))[0] -eq "string"}).name
$sharedprops = (Compare-Object $xml1props $xml2props -IncludeEqual | ? {$_.sideindicator -eq "=="}).inputobject
compare-object $XmlDocument1.html $XmlDocument2.html -Property $sharedprops

答案 1 :(得分:0)

我希望这会有所帮助。我试图明确如何在PowerShell中分析如何处理xml / html,属性和内置/手动比较。

# Import files, casting as xml type.
[xml]$html1 = Get-Content -Path .\1.xml
[xml]$html2 = Get-Content -Path .\2.xml

# Get the members of the html 1's properties where membertype is properties (i.e. the tags)
# See bottom comment for getting tags from both documents
$htmlTags  = ($html1.html | Get-Member | Where-Object {$_.membertype -eq "Property"}).Name

# Put the tags you would like to ignore in an array
$ignoreTheseTags = @("type","ID")

#Loop over the tags, ignoring the ones that you have put in the array
foreach ($tag in $htmlTags | Where-Object {$_ -notin $ignoreTheseTags}){

    # Get the values in this tag.
    $value1 = $html1.html.$tag
    $value2 = $html2.html.$tag

    # You can test to see if the tag is in file 2
    # Continue skips to next tag as Compare-Object will return an error if one of the objects is null
    if($value2 -eq $null){
        Write-Host "Tag $tag is not in html 2`n"
        continue
    }

    # PowerShell built-in comparison operator
    Compare-Object  $value1 $value2

    # Manual case-sensitive value comparison. You can do whatever you want inside the loop
    if($value1 -cne $value2){
        Write-Host "Tag $tag is not equal."
        Write-Host "First file value:  $value1"
        Write-Host "Second file value: $value2`n"
    }

}

<#
#Getting tags from both html documents
$htmlTags  = ($html1.html | Get-Member | Where-Object {$_.membertype -eq "Property"})
$htmlTags += ($html2.html | Get-Member | Where-Object {$_.membertype -eq "Property"})

$htmlTags = ($htmlTags | Select-Object Name -Unique).Name
#>