Powershell diff xml and grab Xpath



我正在尝试区分两个xml文件(IIS web.config),我需要获取发生更改的Xpath。

假设在文件A中,我有:

<configuration>
<system.serviceModel>
<services>
<service name="some service">
<endpoint address= "abc">
</service>
</services>
</system.serviceModel>
</configuration>

在文件B中我有

<configuration>
<system.serviceModel>
<services>
<service name="some other service">
<endpoint address= "xyz">
</service>
</services>
</system.serviceModel>
</configuration>

我正在使用命令

Compare-Object (Get-Content FileA)(Get-Content FileB)

这给了我的输出

<endpoint address= "abc">        =>
<endpoint address= "xyz">        <=

有些文件有多个端点,所以我需要根据它们的绝对Xpath来区分它们,这样我就可以查询回来并用正确的值替换这些值。

有什么想法吗??!!

您想要Xpath,还是实际节点想要?我认为最简单的方法是使用不同的值本身来查找节点(尽管如果存在重复,这可能不会很好地工作):

[xml] $a = Get-Content tempa.xml
[xml] $b = Get-Content tempb.xml
Compare-Object ($a.SelectNodes("//endpoint").address) ($b.SelectNodes("//endpoint").address) |
ForEach-Object {$i = $_.InputObject; switch($_.SideIndicator) {
"=>" { $xpath = "//endpoint[@address='$i']"; @{xpath_b=$xpath; node=$b.SelectNodes($xpath)} }
"<=" { $xpath = "//endpoint[@address='$i']"; @{xpath_a=$xpath; node=$a.SelectNodes($xpath)} }
}}

使用此示例输入(.xml):

<configuration>
<system.serviceModel>
<services>
<service name="some service">
<endpoint address= "abc" />
<endpoint address= "def" />
</service>
</services>
</system.serviceModel>
</configuration>

和(b.xml):

<configuration>
<system.serviceModel>
<services>
<service name="some service">
<endpoint address= "abc" />
<endpoint address= "xyz" />
</service>
</services>
</system.serviceModel>
</configuration>

你会得到这样的输出:

Name    Value                     
----    -----                     
xpath_b //endpoint[@address='xyz']
node    {endpoint}                
xpath_a //endpoint[@address='def']
node    {endpoint}                

但在实践中,您可以直接在switch语句中操作节点,而不是输出这些值。

最新更新