Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting attributes in xml using xpath in powershell

Tags:

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!

like image 849
user1044585 Avatar asked Jul 11 '13 00:07

user1044585


People also ask

How do I get the contents of a XML file in PowerShell?

One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.

How selecting XML data is possible with XPath explain?

XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.


1 Answers

These two lines should suffice:

[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.selectNodes('//person') | select Name
like image 93
Ansgar Wiechers Avatar answered Sep 17 '22 20:09

Ansgar Wiechers