Selecting attributes in xml using xpath in powersh

2020-06-01 01:55发布

问题:

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!

回答1:

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
}


回答2:

These two lines should suffice:

[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.selectNodes('//person') | select Name


回答3:

How about one line?

Select-XML -path "pathtoxml" -xpath "//person/@name"



回答4:

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.