We already discussed the reading/Writing XML file using PowerShell in previous posts. Now in this post, we will discuss how to add the value to the Array or Object from the XML using Powershell.ย
PowerShell has XPath but you don’t have necessarily have to use it. Instead of XPath PowerShell provides the simplest/Easiest way to read XML files, manipulate the XML document, we use the same in the example below.
EMPdetails.xml File
1 2 3 4 5 6 |
<EMPLOYEE_DETAILS> <EMP_NAME>Max</EMP_NAME> <EMP_NAME>John</EMP_NAME> <EMP_NAME>Mike Ban</EMP_NAME> <EMP_NAME>Beny</EMP_NAME> </EMPLOYEE_DETAILS> |
STEP 1:
The simplest way to read an XML document in PowerShell is to typecast a variable to the type [XML]. To create this variable, you can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable. This tells PowerShell that we need this variable typecasted as a System.Xml.XmlDocument type instead of the default array type that normally comes from Get-Content.
$XML1path = “C:\dotnet-helper\EMPdetails.xml”
Once you’ve executed the above cmdlet, the Get-Content cmdlet will read all the raw text from the XML document and cast the output to type System.Xml.XmlDocument, you now have a variable called $XmlDocument that contains the entire XML node tree that represents that document.
STEP 2:
Now you can declare the empty array for getting XML value.
[String[]]$str_EMP_Array = @()
STEP 3:
After the execution of STEP 1, the $XmlDocument variable will have the entire XML node tree. Now you can loop the XML elements from the parent Node. From the below code, you can loop all the child elements by pointing to the parent node.
foreach ($emp_Detail in $XmlDocument.EMPLOYEE_DETAILS.EMP_NAME)
{
[String[]]$str_EMP_Array += $emp_Detail
}
STEP 4:
Finally, print the Array data.
$str_EMP_Array
Final Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
############################################################################ #Project : How to add values to the string Array from xml using Powershell #Developer : Thiyagu S (dotnet-helpers.com) #Tools : PowerShell 5.1.15063.1155 [irp] #E-Mail: mail2thiyaguji@gmail.com ########################################################################### $XML1path = "C:\dotnet-helper\EMPdetails.xml" [String[]]$str_EMP_Array = @() [xml]$XmlDocument = get-content $XML1path foreach ($emp_Detail in $XmlDocument.EMPLOYEE_DETAILS.EMP_NAME) { [String[]]$str_EMP_Array += $emp_Detail } $str_EMP_Array |
Leave A Comment