简体   繁体   中英

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
}

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, ie it would be equivalent to XPath

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM