Reputation: 3896
I have the following XML:
<NET_SETTINGS>
<MAC_ADDRESS VALUE="bb:cc:dd:ee:ff:aa"/>
<IP_ADDRESS VALUE="10.1.1.1"/>
</NET_SETTINGS>
and trying to get the string VALUE
of either mac/ip element like so:
XmlNode macnode = xmlDoc.SelectSingleNode("/NET_SETTINGS/IP_ADDRESS");
string mac = macnode.Value;
I can see that it selects the correct node while stepping through the code, but the macnode.Value
is always null and the OuterXml
is this:
"<MAC_ADDRESS VALUE=\"bb:cc:dd:ee:ff:aa\" />"
Why does Value
not get populated correctly?
Upvotes: 0
Views: 2229
Reputation: 101690
You can actually do this all with one XPath selection:
XmlNode macnode = xmlDoc.SelectSingleNode("/NET_SETTINGS/IP_ADDRESS/@VALUE");
string mac = macnode.Value;
Upvotes: 0
Reputation: 1572
By default the Value property will return the inner of the XML element which does not exist in this case . . .
<MAC_ADDRESS VALUE="bb:cc:dd:ee:ff:aa"/>
is equivalent to . . .
<MAC_ADDRESS VALUE="bb:cc:dd:ee:ff:aa"></MAC_ADDRESS>
The OuterXML will return the entire element markup. So thats why you get the entire element back.
Since you stored it as an attribute you have to refer to it as an attribute
XmlNode macnode = xmlDoc.SelectSingleNode("/NET_SETTINGS/IP_ADDRESS");
string mac = macnode.Attributes.GetNamedItem("VALUE").Value;
Should get you the correct value.
Upvotes: 2
Reputation: 35353
VALUE
is an attribute.
string value = macnode.Attributes["VALUE"].Value
Upvotes: 2
Reputation: 140230
.Value
is null
for Element
nodes.
You want macnode.Attributes.GetNamedItem("VALUE").Value
Upvotes: 4
Reputation: 1079
macnode.Value
is the text value, not the value of the VALUE
attribute. You need the Attributes
property of macnode
, then get the attribute value for the VALUE
attribute from that. See http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.attributes.aspx and http://msdn.microsoft.com/en-us/library/system.xml.xmlattributecollection.aspx
Upvotes: 1