Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text inside an XmlNode

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.

like image 581
joe Avatar asked Dec 06 '22 21:12

joe


1 Answers

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.)

like image 168
Jon Skeet Avatar answered Dec 31 '22 05:12

Jon Skeet