This version uses a bit more PowerShell and handles the case of mulitple items with WorkDir keys:
$xml = [xml](Get-Content foo.xml)
$xpath = "/sections/section/item[@key='WorkDir']"
Microsoft.PowerShell.Utility\Select-Xml $xml -XPath $xpath |
Foreach {$_.Node.SetAttribute('value', $pwd)}
$xml.Save("$pwd\bar.xml")
Note, if you have the PowerShell Community Extensions installed you can use the Format-Xml cmdlet to format the output and save it via Out-File e.g.:
$xml | Format-Xml -AttributesOnNewLine | Out-File bar.xml -enc utf8
OTOH $xml.Save() is easier except that you must remember that it probably doesn't have the correct current dir if you were to specify just the filename. That's why I used "$pwd\bar.xml" in the first example. This is not an issue with PowerShell cmdlets like Out-File.
Вы можете загрузить свой XML в класс LINQ XDocument
из PowerShell следующим образом:
[Reflection.Assembly]::LoadWithpartialName("System.Xml.Linq") | Out-Null
$xDoc = [System.Xml.Linq.XDocument]::Parse($myXmlString)
Оттуда вы можете использовать обычные методы LINQ to XML для замены атрибута как в этот пример . При желании аналогичным образом можно использовать более старый класс XmlDocument
.
Вы можете попробовать это
$xmlFile = "d:\sample.xml"
[xml]$doc = Get-Content $xmlFile
$node = $doc.SelectSingleNode("/sections/section/item[@key='WorkDir']")
$node.Value = "New-Value"
$doc.Save($xmlFile)
Вы по-прежнему будете использовать некоторые классы .Net и запрос XPath для выбора узла.