0

I need to read below xml file and store it in hash table.

<?xml version="1.0"?>
<ConfigValues>
   <Dev>
     <item Key="dbconn" Value ="Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;"/>
   </Dev>
   <QA>
     <item Key="dbconn" Value ="Data Source=xlvxqa.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </QA>
   <PP>
     <item Key="dbconn" Value ="Data Source=xlvxpreprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </PP>
   <PROD>
     <item Key="dbconn" Value ="Data Source=xlvxprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </PROD>
</ConfigValues>

I tried writing below powershell and able to get the attributes key value but I need to store it on the hashtable so that I can retrieve the value as needed.

$URLS = [xml](Get-Content 'C:\Desktop\Variables.xml')

$URLS.ConfigValues.Dev.item | where {$_.key -eq 'connCVRC'}
Key      Value
---      -----
connCVRC Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;
2
  • It's not quite clear what do you want as output, is it $xml.ConfigValues.Dev.Item.Value.Split(';') | ConvertFrom-StringData? Please add an expected result to your question. Commented Jul 20, 2021 at 21:50
  • 1
    Thanks for reach out to me. I was looking for the same results provided in below answer by mklement0 Commented Jul 20, 2021 at 21:59

1 Answer 1

4
# Parse the XML file into an XML DOM
($xml = [xml]::new()).Load((Convert-Path C:\Desktop\Variables.xml))

# Initialize the (ordered) output hashtable.
$hash = [ordered] @{}

# Populate the hashtable with the <ConfigValues> child element 
# names as the key, and their <item> child's Value attribute as the value.
$xml.ConfigValues.ChildNodes.ForEach({
   $hash[$_.Name] = $_.item.Value
})

$hash # output

The above yields:

Name                           Value
----                           -----
Dev                            Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;
QA                             Data Source=xlvxqa.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
PP                             Data Source=xlvxpreprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
PROD                           Data Source=xlvxprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
Sign up to request clarification or add additional context in comments.

1 Comment

My pleasure, @pandeg87. It sounds like this answer solves your problem, but I'm not certain, based on your comment. Either way, please allow me to give you the standard advice to newcomers in the next comment:

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.