ShaQ.Blogs
ShaQ.Blogs

Reputation: 1284

Powershell read XML value

I have the following XML, and I'm trying to obtain the value where the Name attribute is ComponentVersion.

<Component .......>
  <Settings>
    <Setting Name="ComponentVersion" Value="12345" />
    <Setting Name="Host" Value="false" />
  </Settings>
  <Jobs>
    <Job Name="Platform" />
  </Jobs>
</Component>

I read the XML file like this:

$fullPathXML = "$env:PackagesPath\Platform\Components\SystemPlatform.Comp.xml"
[xml]$xmlSystemPlatform = Get-Content $fullPathXML

and then tried the following:

  1. $xmlSystemPlatform.selectNodes('//Settings/Setting') | select Name

  2. Select-Xml '//Settings/Setting[contains(@Name, "ComponentVersion")]' $xmlSystemPlatform |%{$_.Node.Value}

  3. $xmlSystemPlatform.Settings.Setting[0].Name $xmlSystemPlatform.Settings.Setting[0].Value

Upvotes: 0

Views: 1659

Answers (3)

Stoinov
Stoinov

Reputation: 792

Another one-liner:

([Xml] (Get-Content "$env:PackagesPath\Platform\Components\SystemPlatform.Comp.xml")).SelectNodes("//Settings/Setting[@Name='ComponentVersion']").Value

Or if you prefer it with variable:

$xmlSystemPlatform.SelectNodes("//Settings/Setting[@Name='ComponentVersion']").Value

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

Using an XPath expression something like this should work:

$filename = "$env:PackagesPath\Platform\Components\SystemPlatform.Comp.xml"

[xml]$xml = Get-Content $filename

$xml.SelectNodes('//Settings/Setting[@Name = "ComponentVersion"]').Value

Note that XPath expressions are case-sensitive.

Upvotes: 1

user2226112
user2226112

Reputation:

$xmlSystemPlatform.Component.Settings.Setting | ? Name -eq "ComponentVersion" | select Value

Upvotes: 2

Related Questions