我有一個包含許多屬性的 xml 檔案
<configuration>
<property>
<name>access.key</name>
<value>fred</value>
</property>
<property>
<name>access.secret</name>
<value>blog</value>
</property>
</configuration>
我想根據屬性名稱替換屬性值。我嘗試了多種方法。我遇到了問題,因為名稱和值是屬性的元素而不是屬性。我雖然這會奏效,但沒有運氣。
$file = "site.xml"
$xml = New-Object XML
$xml.Load($file)
$nodes = $xml.SelectNodes('/configuration/property')
foreach ($node in $nodes) {
$property = $node.Attributes.GetNamedItem("name").Value
if ($property -eq 'access.key')
{
$node.Attributes.SetNamedItem("value").Value = '{{ access_key }}'
}
}
$xml.Save($file)
以下更改了,但它更改了 name 的值,這是有道理的,因為我選擇了 SingleNode 屬性名稱。如何根據名稱更改屬性值?
$node = $xml.SelectSingleNode("/configuration/property/name[.= 'access.key']")
$node.innerText = '{{ access_key }}'
這看起來很簡單,可能是,希望有人能有所啟發。
uj5u.com熱心網友回復:
我使用您包含的 .xml 的內容進行測驗,我認為下面的腳本可以滿足您的要求。
我洗掉了$property變數,只是將If陳述句更改為要求與$node.name您要查找的名稱相同。如果是,那么它將$node.value在完成ForEach回圈后更新并保存 .xml :
$file = "site.xml"
$xml = New-Object XML
$xml.Load($file)
$nodes = $xml.SelectNodes('/configuration/property')
foreach ($node in $nodes) {
if ($node.name -eq 'access.key')
{
$node.Value = '{{ access_key }}'
}
}
$xml.Save($file)
uj5u.com熱心網友回復:
有多種方法可以做到這一點:
$fileName = 'D:\Test\site.xml'
$xml = New-Object -TypeName 'System.Xml.XmlDocument'
$xml.Load($fileName)
$xml.DocumentElement.ChildNodes | Where-Object { $_.name -eq 'access.key' } | ForEach-Object { $_.name = 'access_key' }
# or
# $xml.configuration.property | Where-Object { $_.name -eq 'access.key' } | ForEach-Object { $_.name = 'access_key' }
# or
# $xml.SelectNodes("//property/name[text() = 'access.key']") | ForEach-Object { $_.innerText = 'access_key' }
$xml.Save($fileName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/374218.html
