renatotkr
renatotkr

Reputation: 68

Foreach on XML returning string

I'm trying to read an XML file via PowerShell.

Sample XML:

<branches>
    <branch>refs/heads/master</branch>
    <branch Version="6.0.7">develop/4.0</branch>
</branches>

Sample code:

$xml = [xml](Get-Content $xmlfile)
foreach ($branch in $xml.branches.branch) {
    $version = $branch.Version
}

The problem is that the attribute Version is optional and PowerShell interprets the first occurrence of branch as a string. The second occurrence works fine. I need both of them to be an XmlElement. I have already tried casting $xml.branches.branch to an array of XmlElements with no success.

How can I transform to XmlElement?

Upvotes: 0

Views: 85

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Use SelectSingleNode() with an XPath expression rather than dot-access:

$version = $xml.SelectSingleNode('//branches/branch/@Version').'#text'

Upvotes: 1

Related Questions