Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlNode Value vs InnerText

Tags:

c#

.net

xml

I'm creating a ping application for school with an XML full of URLs. I lost an hour because of XmlNode.Value was resulting in a null.

Then I changed it into InnerText and it worked fine.

Now I was wonder what's the difference because MSDN says that .Value returns the value of the node and InnerText returns the concatenated values of the node and all its child nodes.

Can someone explain this for me please?

<sites> <site>     <url>www.test.be</url>     <email>[email protected]</email> </site> <site>     <url>www.temp.be</url>     <email>[email protected]</email> </site> <site>     <url>www.lorim.ipsum</url>     <email>[email protected]</email> </site></sites> 
like image 275
Tom Kerkhove Avatar asked Oct 24 '11 14:10

Tom Kerkhove


People also ask

What is InnerText in XML?

The InnerText property represents the concatenation of all child text nodes. Setting the InnerText property replaces all child nodes with a single text node.

What is value of XML node?

The Value property of that XmlText node would be "Bar". "Foo" is considered to be an XmlElement (also sub-classed from XmlNode ).


2 Answers

If, for example, your XML looks like <Foo>Bar</Foo> then "Bar" is actually considered a separate node: an XmlText node (sub-classed from XmlNode). The Value property of that XmlText node would be "Bar".

"Foo" is considered to be an XmlElement (also sub-classed from XmlNode). XmlNode.Value returns different things based on the type of node it is. See this table which shows that Value always returns null for Element nodes.

The InnerText of the Foo node returns "Bar" because it concatenates the values of its children (in this case, only the one XmlText node).

like image 190
Robert Levy Avatar answered Oct 11 '22 09:10

Robert Levy


I had a similar situation. What I did is, I picked the first child of the current node and checked if it is XMLtext, then displayed its value.

XmlNodeList xNList = xDOC.SelectNodes("//" + XMLElementname);  foreach (XmlNode xNode in xNList) {     if (xNode.ChildNodes.Count == 1 &&          xNode.FirstChild.GetType().ToString() == "System.Xml.XmlText")     {         XMLElements.Add(xNode.FirstChild.Value);     }     else     {         XMLElements.Add("This is not a Leaf node");     } } 
like image 22
Santhosh Murali Avatar answered Oct 11 '22 07:10

Santhosh Murali