我一直在寻找多种解释,但似乎无法找到解决方案。
我的 XML 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<ConfigRightCollection>
<ConfigRight Name="CreateSampling">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="InputMeasure">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="AllowCreateOnStoppedJob">
<GroupCollection>
<Group>Admin</Group>
</GroupCollection>
</ConfigRight>
</ConfigRightCollection>
我想向 'ConfigRight Name = "AllowCreateOnStoppedJob' 组添加新元素,使其看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<ConfigRightCollection>
<ConfigRight Name="CreateSampling">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="InputMeasure">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="AllowCreateOnStoppedJob">
<GroupCollection>
<Group>Admin</Group>
<Group>QS</Group>
<Group>QU</Group>
</GroupCollection>
</ConfigRight>
</ConfigRightCollection>
我的代码到目前为止似乎有效:
$filePath = "\\some\path\to\the\file.xml"
[xml]$xmlData = Get-Content -Path $filePath
$xmlData | Select-Xml -XPath '/ConfigRightCollection/ConfigRight' | Where-Object{ ($_.Node.Name -eq "AllowCreateOnStoppedJob") } | Select-Object -ExpandProperty "Node"
但是实际添加新元素的代码不起作用,我收到错误“无法在空值表达式上调用方法”:
$newGroups = "QS","QU"
ForEach ($group in $newGroups)
{
# Creation of a sub node
$xmlSubElt = $xmlData.GroupCollection.CreateElement("Group")
$xmlSubText = $xmlData.GroupCollection.CreateTextNode($group)
$xmlSubElt.AppendChild($xmlSubText)
}
$xmlData.Save
我似乎无法解决的部分是如何选择正确的 ConfigRight 元素并向其 GroupCollection 子元素添加 2 个新元素?我仅限于 PS 5.1
使用 Xml Linq
using assembly System.Xml.Linq
$inputFilename = "c:\temp\test.xml"
$outputFilename = "c:\temp\tes1.xml"
$doc = [System.Xml.Linq.XDocument]::Load($inputFilename)
$configRight = $doc.Descendants("ConfigRight")
$allowCreateOnStoppedJob = [System.Linq.Enumerable]::Where($configRight, [Func[object,bool]]{ param($x) [string]$x.Attribute("Name").Value -eq "AllowCreateOnStoppedJob"})[0]
$groupCollection = $allowCreateOnStoppedJob.Element('GroupCollection')
$group = [System.Xml.Linq.XElement]::new([System.Xml.Linq.XName]::Get('Group'),'QS')
$groupCollection.Add($group)
$group = [System.Xml.Linq.XElement]::new([System.Xml.Linq.XName]::Get('Group'),'QU')
$groupCollection.Add($group)
$doc.Save($outputFilename)