[英]Powershell script to add XML sub-elements
我快疯了。 我需要在 powershell 中修改这个 XML 文件
<Smart>
<Settings>
<Section name="x">
<Parameter name="a" value="true" />
<Parameter name="b" value="0" />
<Parameter name="c" value="13873" />
<Parameter name="d" value="true" />
<Parameter name="e" value="EAI" />
</Section>
<Section name="z">
<Parameter name="h" value="true" />
<Parameter name="i" value="0" />
<Parameter name="j" value="13873" />
<Parameter name="k" value="true" />
<Parameter name="l" value="EAI" />
</Section>
</Settings>
</Smart>
我想要做的是添加另一行,例如:
< 参数名称="f" 值="OK" />
但我想在第一个 Section < Section name="x"> 中添加新行
#Modify XML file
Write-Host "OPENING XML FILE";
$path = "\\$computer\$FileName"
[xml] $xml = Get-Content $path
#return $xml.SmartUpdate.Settings.Section.Parameter
#set values for the XML nodes you need. This uses the XPath of the value needed.
**WANT TO ADD THE NEW PARAMETER HERE**
#Save the file
$xml.save($path)
Write-Host "XML FILE SAVED";
我找不到解决方案。 请帮我
像这样的东西应该工作。 请注意,我的 XML 技能与 Powershell 远非好,所以我希望其他人有更好的解决方案
# Create a new node
$NewNode = $Xml.CreateNode([System.Xml.XmlNodeType]::Element,"Parameter",$null)
# create the attributes and set the values
$NameAttribute = $XMl.CreateAttribute('name')
$NameAttribute.Value = 'f'
$ValueAttribute = $Xml.CreateAttribute('value')
$ValueAttribute.Value = 'OK'
# append the attributes
$NewNode.Attributes.Append($NameAttribute)
$NewNode.Attributes.Append($ValueAttribute)
# append the new node to the correct parent
$Xml.Smart.Settings.Section.AppendChild($NewNode)
由于您有多个Section
节点,因此您需要将新的子节点指定为 append 到:
$path = "\\$computer\$FileName"
[xml]$xml = Get-Content -Path $path -Raw
# create a new childnode and append attributes to it
$childNode = $xml.CreateElement("Parameter")
$attrib = $xml.CreateAttribute('name')
$attrib.Value = 'f'
[void]$childNode.Attributes.Append($attrib)
$attrib = $xml.CreateAttribute('value')
$attrib.Value = 'OK'
[void]$childNode.Attributes.Append($attrib)
# select the parent node to append this childnode to
$parentNode = $xml.Smart.Settings.Section | Where-Object { $_.name -eq 'x' }
[void]$parentNode.AppendChild($childNode)
$xml.Save($path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.