用于 XML 比较的 Powershell 脚本

Powershell script for XML comparision

我正在尝试使用 powershell 脚本比较 web.config 生产文件和非生产文件。我能够生成可以比较到一个级别的代码,但除此之外,我没有在互联网上找到任何帮助来比较和更新具有多级深度节点结构的 xml 文件。下面是我的代码,它可以在文件的第一层工作,但不会超出。有什么方法可以比较两个文件并更新而无需对任何节点元素进行硬编码?下面是我的代码,它可以达到一个级别。

$src_web_config = "C:\Users\live\web.config"
$dst_web_config = "C:\Users\int\web.config"

# Creating XML objects for live and integration
$src_xml = New-Object -TypeName XML
$dst_xml = New-Object -TypeName XML
$src_xml.Load($src_web_config)
$dst_xml.Load($dst_web_config)

# get top nodes
$src_top_node = $src_xml.DocumentElement.Name
$dst_top_node = $dst_xml.DocumentElement.Name


function add_node($add_node)
{
    Write-Host "Node", $add_node.name, "doesn't exist"
    $node = $dst_xml.importnode($add_node, $true)
    $dst_xml.$dst_top_node.appendchild($node)
    $dst_xml.Save($dst_web_config)
}

if ($src_top_node -eq $dst_top_node)
{
    if ($src_xml.$src_top_node.HasChildNodes)
    {
        $src_xml.$src_top_node.ChildNodes | % {
            if ($dst_xml.$dst_top_node.ChildNodes.name -contains $_.name)
            {
                if ($_.haschildnodes)
                {
                    #nothing I can find                    
                }
            }
            else
            {  
                add_node($_)   
            }
        }
     }
}

此致, Vj

微软有 XML Diff and Patch Tool that you can use in a .NET application. Microsoft also provides a sample GUI Tool written in C# that uses the library. You can download the GUI source code installer from here.

我对使用 Powershell 的 XML Diff 库没有任何特别的建议。从 Powershell 使用 .NET 库是另一个主题,但您可以在线找到有关它的信息。如果您不致力于 Powershell,也许您可​​以使用 C# 或 VB.NET 代替,就像在 GUI 工具中一样。如果您不需要编写自己的脚本来自动执行该过程,您可以使用他们的 GUI 工具根据需要区分 XML 文件。