Haripriya1998
Haripriya1998

Reputation: 33

Looping through XML file with Powershell

I am trying to run a 'for' loop that parses the below XML file such that I am able to take in the descendants of books as parameters. Aka for each book, I want to be able to associate the Publisher, Author and type of book with the name of the book to be used as parameters subsequently in Powershell Script.

<config>
    <Book name="ABC">
        <property name="Publisher" value="XYZ"/>
        <property name="Author" value="Meow"/>
        <property name="Type" value="Fiction"/>
    </Book>
    <Book name="DEF">
        <property name="Publisher" value="wow"/>
        <property name="Author" value="Bark"/>
        <property name="Type" value="NonFiction"/>
    </Book>
    <Email>
        <Name>XXXXXX</Name>
        <Name>XXXXXX</Name>
    </Email>
</config>

The following is the code that I am currently using but it does not suit my needs.

[xml]$xml = [xml] (Get-Content $File)
$nodes=$xml.SelectNodes("config/child::Book")

foreach($node in $nodes){
   $sid=$node.attributes['name'].value
   $value=$node.attributes['value'].value
   $sid 
   $value
   "-------------------------------"
}

Upvotes: 3

Views: 3146

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19694

You can simplify what you're doing by traversing the Books as an array:

$xml = [xml](Get-Content -Path $path)

$collection = foreach ($book in $xml.config.Book) {
    $out = [ordered]@{
        sid = $book.Name
    }

    for ($i = 0; $i -lt $book.property.Count; $i++) {
        $out[$book.property.name[$i]] = $book.property.value[$i]
    }

    [pscustomobject]$out
}

Now $collection is an array of objects you can more easily filter with the keys SID, Publisher, Author, and Type, i.e.,

$collection | Where-Object sid -eq 'ABC'

Upvotes: 4

Related Questions