我是探索 XML 到 Powershell 的新手。我在這里有一個示例 XML,我需要編輯該值。
示例 XML
<Configuration>
<System>
<Address link = "http://www.thispage.com" page = "first" />
<Address link = "http://www.thispage.com" page = "second"/>
</System>
</Configuration>
這是我編輯 XML 時的“應該是結果”。
<Configuration>
<System>
<Address link = "https://www.thispage.com" page = "first" />
<Address link = "https://www.thispage.com" page = "second"/>
</System>
</Configuration>
我試過這個代碼:
$fileName = "C:\Project\XML-file\SampleXML.config"
$xmlContent = [xml](Get-Content $fileName)
$xmlContent | Select-Xml -XPath 'Configuration/system/Address' | ForEach-Object {$_.node.link -replace 'http','https'}
$xmlContent.save($fileName)
在這段代碼中,該值沒有被替換,但檔案正在被保存(檔案沒有更改)。但我可以在 Powershell 控制臺中看到http被https替換
我也嘗試過SetAttribute命令,但它正在替換鏈接的整個值。前任:
<Configuration>
<System>
<Address link = "https" page = "first" />
<Address link = "https" page = "second"/>
</System>
</Configuration>
感謝您的投入!
uj5u.com熱心網友回復:
您的 xml 沒有正確關閉</Configuration>。
要加載 xml,最好使用下面的方法然后使用$xmlContent = [xml](Get-Content $fileName),因為該.Load()方法確保您獲得正確的檔案編碼。
嘗試
$fileName = "C:\Project\XML-file\SampleXML.config"
$xmlContent = New-Object -TypeName 'System.Xml.XmlDocument'
$xmlContent.Load($fileName)
$xmlContent.DocumentElement.System.ChildNodes | ForEach-Object { $_.link = $_.link -replace '^http:', 'https:' }
# or
# $xmlContent.Configuration.System.Address | ForEach-Object { $_.link = $_.link -replace '^http:', 'https:' }
# or
# $xmlContent.SelectNodes('//Address') | ForEach-Object { $_.SetAttribute('link', ($_.GetAttribute('link') -replace '^http:', 'https:')) }
$xmlContent.Save($fileName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/372595.html
