Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
Is there a reliable way to get the selected element's names after applying an XPath expression with select-xml

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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')
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!