0

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.

1
  • 1
    Why are you not using the built-in Powershell Xml cmdlets or the XML .Net names space to parse the XML for what you want? Commented May 26, 2021 at 10:44

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.