Get XML attribute values

by slash85 at 2012-09-24 01:50:44

Hi all,

I’m trying to store the XML attribute values from this command:

[xml]$userfile = get-content test.xml

$NAME = $userfile | select-xml -xpath “//NAME//@SNAME

$NAME


However this does not output the value only the node information (as below)

Node Path Pattern
---- ---- -------
SNAME InputStream //NAME//@SNAME
SNAME InputStream //NAME//@SNAME
SNAME InputStream //NAME//@SNAME

How can i retrieve the actual values in SNAME and store in a variable?

Many Thanks for any help - i’m sure it’s easy but i’m not having much luck.

I’ve tried piping to | foreach {$_.value} but still nothing?

Slash.
by DonJ at 2012-09-24 06:34:39
I’m not the awesome-est at XML manipulation, but in general you’ll want to pipe whatever you’ve got to Get-Member. That’ll show you what it’s made of. Could you post a short excerpt of your XML? Not the whole thing, just a short version. It’s hard to help you with this without knowing what the input looks like.
by surveyor at 2012-09-24 07:28:54
Hi slash,
with a little modification from this thread it shows maybe what you need:
Clear-Host

$myxml = [xml]@"
<?xml version=“1.0” encoding=“utf-8” standalone=“no” ?>
<fieldData>
<map name=“Default” numFields=“34” maxCoords=“60”>
<field name=“Field 1” area=“27846” hectares=“2.784600019455” acres=“6.880747795105”>
<coordinates startX=“693” startZ=“92” endX=“707” endZ=“96” />
<coordinates startX=“693” startZ=“97” endX=“722” endZ=“101” />
<coordinates startX=“688” startZ=“102” endX=“737” endZ=“106” />
<status num=“2” density=“105448” />
</field>
<field name=“Field 2” area=“10373” hectares=“1.037299990654” acres=“2.5631682872772”>
<coordinates startX=“911” startZ=“161” endX=“1025” endZ=“165” />
<coordinates startX=“906” startZ=“166” endX=“1025” endZ=“180” />
<coordinates startX=“901” startZ=“181” endX=“1025” endZ=“195” />
<status num=“2” density=“40516” />
<fruit name=“wheat”>
<growth num=“5” density=“39828” />
</fruit>
</field>
<field name=“Field 3”>
Testtext
</field>
</map>
</fieldData>
"@

# get attributes
$Field2 = Select-Xml -Xml $myxml -XPath “/fieldData/map/field[@name=‘Field 2’]”
$Field2.Node.area

# get the value
$Field3 = Select-Xml -Xml $myxml -XPath “/fieldData/map/field[@name=‘Field 3’]”
$Field3.Node.InnerText
# or better
$Field3.Node.InnerText.Trim()