allendehl
allendehl

Reputation: 129

How to make the following edit to an XML file?

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

Answers (2)

Ash
Ash

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

JPBlanc
JPBlanc

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

Related Questions