How to get text inside an XmlNode

joe picture joe · Jun 7, 2011 · Viewed 26.6k times · Source

How do I get the text that is within an XmlNode? See below:

XmlNodeList nodes = rootNode.SelectNodes("descendant::*");
for (int i = 0; i < nodes.Count; i++)
{
    XmlNode node = nodes.Item(i);

    //TODO: Display only the text of only this node, 
   // not a concatenation of the text in all child nodes provided by InnerText
}

And what I ultimately want to do is preppend "HELP: " to the text in each node.

Answer

Jon Skeet picture Jon Skeet · Jun 7, 2011

The simplest way would probably be to iterate over all the direct children of the node (using ChildNodes) and test the NodeType of each one to see if it's Text or CDATA. Don't forget that there may be multiple text nodes.

foreach (XmlNode child in node.ChildNodes)
{
    if (child.NodeType == XmlNodeType.Text ||
        child.NodeType == XmlNodeType.CDATA)
    {
        string text = child.Value;
        // Use the text
    }
}

(Just as an FYI, if you can use .NET 3.5, LINQ to XML is a lot nicer to use.)