Reputation: 129
I have an XML file encoded in UTF-8 similar to the one below and need to update it conditionally using PowerShell
<Group>
<Entry>
<String>
<User>UserOne</User>
</String>
<String>
<Key>URL</Key>
<Value>Test</Value>
</String>
</Entry>
<Entry>
<String>
<User>UserTwo</User>
</String>
<String>
<Key>URL</Key>
<Value></Value>
</String>
</Entry>
</Group>
I need to update those URLs who have a "blank" Value to a predetermined text.
Upvotes: 1
Views: 51
Reputation: 3246
This should work, but I suspect there will be better solutions.
$xml = [System.Xml.XmlDocument](Get-Content .\Desktop\test.xml -Raw)
$urls = $xml.SelectNodes("//Key") | Where-Object { $_.InnerText -eq "URL" }
foreach ($url in $urls) {
if ([string]::IsNullOrEmpty($url.NextSibling.InnerText)) {
$url.NextSibling.InnerText = "predetermined text"
}
}
$xml.Save(".\Desktop\test.xml")
Upvotes: 3
Reputation: 72670
You can inspire from that, but not better than @ash answer :
[xml]$xml = @"
<Group>
<Entry>
<String>
<User>UserOne</User>
</String>
<String>
<Key>URL</Key>
<Value>Test</Value>
</String>
</Entry>
<Entry>
<String>
<User>UserTwo</User>
</String>
<String>
<Key>URL</Key>
<Value></Value>
</String>
</Entry>
</Group>
"@
$users = $xml.selectNodes("//Group/Entry")
foreach ($user in $users)
{
Write-Host "Enter URL for $($user.String[0].User)"
$url = Read-Host
$user.String[1].Value = [string]$url
}
$xml.Save("c:\temp\FileAfter.xml")
Upvotes: 1