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!
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.
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.
These two lines should suffice:
[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.selectNodes('//person') | select Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With