Thursday, May 09, 2013

Getting a Single Value Out of XMLElement.InnerText

Symptom:

Suppose you have the following XML (and succesfully navigated down to the first element in the line below using something like Eelement.Select(@"//element"); etc.
<element>a
<element>b
</element>
</element>
If your mind is like mine, you probably thought that
  1. Element.Value would give you "a". Element.Value actually won't give you anything.
  2. Element.InnerText would give you "a". That is not true either, it will give you "ab" since it returns all of the text of the children.
How do you extract the string "a" out of this.

First off the answer (2) is more correct one. But we forget that everything in XML are linked nodes. Therefore the Text part which comprises of "a" is technically a child node of the first element.


No comments: