Orest Gulman
Orest Gulman

Reputation: 432

conditionally removechild in xml using powershell

I have an xml configuration file:

<?xml version="1.0"?>
<Tenant>
  <Tenants>
    <Tenant name="tenant_0" siteName="t100001" urlWebSite="qa.local" username="admin" password="admin" />
    <Tenant name="tenant_1" siteName="t100002" urlWebSite="qa.local" username="admin" password="admin" />
    <Tenant name="tenant_2" siteName="t100003" urlWebSite="qa.local" username="admin" password="admin" />
    <Tenant name="tenant_3" siteName="t100004" urlWebSite="qa.local" username="admin" password="admin" />
  </Tenants>
<Tenant>

Currently, I'm modifying each urlWebSite attribute with a new value $urlWebSite:

$urlWebSite = 'prod.local'
$siteName = @('t100001','t100002','t100003')

[xml]$config = Get-Content("path\xml.config")
    Foreach($i in $config.Tenant.Tenants.childnodes){
        $i.urlWebSite = "$UrlWebSite"
        }
$config.save("path\xml.config")

I also need to remove a childnode from Tenants in case if childnode has siteName attribute witch is NOT in $siteName array.

Upvotes: 0

Views: 48

Answers (1)

Theo
Theo

Reputation: 61068

The xml you show is invalid, because the final <Tenant> should be a closing tag: </Tenant>.

Having fixed that, here's your code revised:

# Best use below method to load an XML from file, because it automatically detects the file encoding
$config = New-Object System.XML.XMLDocument
$config.Load("path\xml.config")

$urlWebSite = 'prod.local'
$siteNames  = 't100001','t100002','t100003'  # don't need '@()' here. The comma is enough to create an array

foreach ($node in $config.Tenant.Tenants.Tenant) {
    if ($siteNames -contains $node.siteName) {
        # reset the attributes value
        $node.SetAttribute('urlWebSite', $urlWebSite)
    }
    else {
        # not in the $siteNames array, so remove this node
        $null = $node.ParentNode.RemoveChild($node)
    }
}

$config.save("path\xml.config")

Output:

<?xml version="1.0"?>
<Tenant>
  <Tenants>
    <Tenant name="tenant_0" siteName="t100001" urlWebSite="prod.local" username="admin" password="admin" />
    <Tenant name="tenant_1" siteName="t100002" urlWebSite="prod.local" username="admin" password="admin" />
    <Tenant name="tenant_2" siteName="t100003" urlWebSite="prod.local" username="admin" password="admin" />
  </Tenants>
</Tenant>

Upvotes: 2

Related Questions