kumar
kumar

Reputation: 9407

how do i list all the attribute name in an xml using powershell

Using powershell how do I get the list of attributeNames.

  <productSettings>
    <productGroups>
      <productGroup attributeName1="1" 
                    attributeName2="1" 
                    attributeName3="xyz" 
                    attributeName4="0"/>
    </productGroups>
  </productSettings>

When I try to use the Atrributes property I get the attribute values not the name of the attribute

[xml]$config = Get-Content 'C:\\ProductGroup.config'

$configNodes = $config.productSettings.productGroups.ChildNodes

foreach($configNode in $configNodes)
{
    $configNode.Attributes
}

Upvotes: 0

Views: 309

Answers (1)

Tomalak
Tomalak

Reputation: 338316

Traditional approach: Iterate the attributes and output their names:

foreach ($configNode in $configNodes) {
    foreach ($attr in $configNode.Attributes) {
        $attr.Name
    }
}

PowerShell approach: In PowerShell 3.0+ you can use dot notation on collections to access nested properties:

foreach ($configNode in $configNodes) {
    $configNode.Attributes.Name
}

In fact you could go as far as

$config.productSettings.productGroups.productGroup.Attributes.Name

which would produce all attribute names across all <productGroup> elements, i.e. it would be equivalent to XPath

/productSettings/productGroups/productGroup/@*/name()

Upvotes: 1

Related Questions