How to read the XML file in PowerShell?


Reading the XML file in PowerShell is easy. We have the below XML file for our example,

Example

<Animals>
     <Animal Name="Elephant" Type="Wild">
            <Residence>Forest</Residence>
            <Color>Brown</Color>
      </Animal>

     <Animal Name="Dog" Type="Pet">
            <Residence>Street</Residence>
            <color>Multi</color>
      </Animal>

     <Animal Name="Tiger" Type="Wild">
            <Residence>Forest</Residence>
            <color>Yellow</color>
    </Animal>
</Animals>

Suppose this file is saved as Animals.xml to our current path and to read this XML file we will first get the content of the file using Get-Content command and then we will perform type conversion into XML. For example,

Example

[XML]$xmlfile = Get-Content .\Animals.xml

When you check the $xmlfile output,

Output

PS E:\scripts\Powershell> $xmlfile

Animals
-------
Animals

Animals tag is called element here and to get the attributes from the element, we need to use that element, for example,

Example

$xmlfile.Animals

PS E:\scripts\Powershell> $xmlfile.Animals

Animal
------
{Elephant, Dog, Tiger}

Similarly, you can use Animal elements to expand further attributes, and so on. For example,

Example

$xmlfile.Animals.Animal

PS E:\scripts\Powershell> $xmlfile.Animals.Animal

Name     Type Residence Color
----     ---- --------- -----
Elephant Wild Forest    Brown
Dog      Pet  Street    Multi
Tiger    Wild Forest    Yellow

To get a specific attribute like Name, Type, etc.

$xmlfile.Animals.Animal.name

Output

PS E:\scripts\Powershell> $xmlfile.Animals.Animal.name
Elephant
Dog
Tiger

To get the Type of the animal.

$xmlfile.Animals.Animal.Type

Output

PS E:\scripts\Powershell> $xmlfile.Animals.Animal.Type
Wild
Pet
Wild

If you want two or more attributes together in the table format then you can use PowerShell traditional Select or Format-Table command. For example,

Example

$xmlfile.Animals.Animal | Select Name, Type

Output

PS E:\scripts\Powershell> $xmlfile.Animals.Animal | Select Name, Type

Name     Type
----     ----
Elephant Wild
Dog      Pet
Tiger    Wild

Updated on: 11-Nov-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements