【发布时间】:2020-10-05 23:21:34
【问题描述】:
我有 2 个名为 ConfigA.config(源文件)和 ConfigB.config(目标文件)的 XML 文件。 XML文件如下
源文件:- ConfigA.config
<?xml version="1.0" encoding="utf-16"?>
<Configuration>
<Data>
<Section EntityID="GUID1">
<Item Name="Name_Value" Layer="Some_Layer" Type="Custom" RootNamespace="Some.API.User"
FileName="SomeFileName" />
</Section >
<Section EntityID="GUID2">
<Item Name="Name_Value1" Layer="Some_Layer1" Type="Custom1" RootNamespace="Some.API.User1"
FileName="SomeFileName1" />
</Section >
</Data>
</Configuration>
目标文件:- ConfigB.config
<?xml version="1.0" encoding="utf-16"?>
<Configuration>
<Data>
<Section EntityID="GUID1">
<Item Name="Name_Value2" Layer="Some_Layer2" Type="Custom2" RootNamespace="Some.API.User2"
FileName="SomeFileName2" />
</Section>
</Data>
</Configuration>
我需要做以下事情
- 使用 EntityId 属性检查目标文件中是否存在节点?
- 如果节点存在,则从目标文件中删除节点并将节点从源文件附加到目标文件
- 如果节点不存在,则将节点从源文件追加到目标文件。
我尝试过的:-
我编写了以下 powershell 脚本,它迭代两个文件节点并检查节点是否存在于目标文件中,如果节点存在,它将从源文件中删除并附加节点。脚本如下
[xml] $serverFile = Get-Content -Path 'C:\demo\server\ConfigB.config'
[xml] $localFile = Get-Content -Path 'C:\demo\local\ConfigA.config'
foreach($i in $localFile.Configuration.Data.Section) {
$serverFile.Configuration.Data.Section |
? { $_.EntityID -eq $i.EntityID } |
% {
$entityId = $_.EntityID
Write-Output $entityId
$SourceXmlNode = $localFile | Select-Xml -XPath "//Section[@EntityID = '$entityId']"
$parent = $_.ParentNode
[void]$_.ParentNode.RemoveChild($_)
[void] $parent.AppendChild($serverFile.ImportNode($SourceXmlNode.Node, $true))
}
}
$serverFile.Save('C:\demo\server\ConfigB.config')
按照堆栈溢出已经问答帮助我删除和附加节点的东西。
Copy XML node from one file and append it to another XML file.
问题:-
现在,借助上面的代码,如果该节点存在于目标中,我可以删除并附加节点。它工作正常。但是如果目标文件中不存在新节点,我正在努力添加新节点。
问题:-
- 有什么方法可以添加 else 部分,以便我可以添加与将新节点从源文件添加到目标文件相关的逻辑?
- 如果没有办法添加 else 部分。如何更改上述脚本,以便检查 if-else 条件?
- 有没有更好的方法来实现这一点?
【问题讨论】:
标签: xml powershell