Selecting attributes in xml using xpath in powershell

后端 未结 4 2053
醉梦人生
醉梦人生 2020-12-15 06:48

I am trying to use powershell and XPath to select the name attribute shown in the below xml example.

     $xml_peoples= $file.SelectNodes(\"//people\") 
             


        
相关标签:
4条回答
  • 2020-12-15 07:08

    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
    }
    
    0 讨论(0)
  • 2020-12-15 07:13

    These two lines should suffice:

    [xml]$xml = Get-Content 'C:\path\to\your.xml'
    $xml.selectNodes('//person') | select Name
    
    0 讨论(0)
  • 2020-12-15 07:21

    How about one line?

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

    0 讨论(0)
  • 2020-12-15 07:26

    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.

    0 讨论(0)
提交回复
热议问题