I am struggling to find a reliable way to determine the names of elements that were selected by an XPath expression using the PowerShell cmdlet select-xml:
$xml = select-xml -content @'
<root>
<A name='foo' localname='FOO'/>
<B name='bar' />
<C id ='baz' localname='BAZ'/>
<D />
</root>
'@ -XPath '/root/*'
[System.Xml.XmlElement] $elem = $null
foreach ($elem in $xml.Node) {
"name = $($elem.name), localname = $($elem.localname)"
}
This code prints
name = foo, localname = FOO
name = bar, localname = B
name = C, localname = BAZ
name = D, localname = D
Apparently, the XML attributes name and localname interfere with the .NET class attributes with the same names. So, is there a construct that returns A, B, C and D for the above example.
XMLElement class allows matching attribute names and XMLElement class property names. In that case, the attribute names take precedence during member access (object.property). The properties created when XMLElement object is instanced can be retrieved with Get_ methods (Get_Name() and Get_LocalName() in this scenario). The attributes names can be retrieved with the GetAttribute method to ensure a consistent experience.
$xml = select-xml -content @'
<root>
<A name='foo' localname='FOO'/>
<B name='bar' />
<C id ='baz' localname='BAZ'/>
<D />
</root>
'@ -XPath '/root/*'
$xml.Node |% {
# XMLElement class property Name and LocalName values
"Name = {0}, LocalName = {1}" -f $_.Get_Name(),$_.Get_LocalName()
# Value of attributes name and localname
"name = {0}, localname = {1}" -f $_.GetAttribute('name'),$_.GetAttribute('localname')
}