I am trying to use powershell and XPath to select the name attribute shown in the below xml example.
$xml_peoples= $file.SelectNodes("//people")
foreach ($person in $xml_peoples){
echo $person.attributes
#echo $person.attributes.name
}
Above is the code im running to try and get the name, but it doesn't seem to work. Any suggestions?
<peoples>
<person name='James'>
<device>
<id>james1</id>
<ip>192.192.192.192</ip>
</device>
</person>
</peoples>
Thanks in advance!
I'm not sure what $hub is, and you started your code from the middle so it's not clear if you properly set $file to an XmlDocument object, but I think this is what you want:
[System.Xml.XmlDocument]$file = new-object System.Xml.XmlDocument
$file.load(<path to XML file>)
$xml_peoples= $file.SelectNodes("/peoples/person")
foreach ($person in $xml_peoples) {
echo $person.name
}
These two lines should suffice:
[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.selectNodes('//person') | select Name
How about one line?
Select-XML -path "pathtoxml" -xpath "//person/@name"
For anyone that has to work around Select-Xml's garbage namespace handling, here's a one-liner that doesn't care, as long as you know the direct path:
([xml](Get-Content -Path "path\to.xml")).Peoples.Person.Name
The above will return all matching nodes as well. It's not as powerful, but it's clean when you know the schema and want one thing out of it quickly.