How to get text inside XmlNode

How to get text that is in 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 the "HELP:" prefix for the text in each node.

+3
source share
4 answers

The simplest way would probably be to loop over all the direct children of the node (using ChildNodes) and test NodeTypeeach one to see if it is Textor CDATA. Do not forget that there may be several 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 like FYI, if you can use .NET 3.5, it is better to use LINQ to XML.)

+9
source

Find the children node for node with NodeTypefrom Textand use the property Valuefor this node.

, XPath text() node.

+3

you can read the InnerText property for xmlnode read node.InnerText

+1
source

check this

You can also check what parameters you get when you write "reader."

xml file

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<ISO_3166-1_List_en xml:lang="en">
   <ISO_3166-1_Entry>
      <ISO_3166-1_Country_name>SINT MAARTEN</ISO_3166-1_Country_name>
      <ISO_3166-1_Alpha-2_Code_element>SX</ISO_3166-1_Alpha-2_Code_element>
   </ISO_3166-1_Entry>
   <ISO_3166-1_Entry>
      <ISO_3166-1_Country_name>SLOVAKIA</ISO_3166-1_Country_name>
      <ISO_3166-1_Alpha-2_Code_element>SK</ISO_3166-1_Alpha-2_Code_element>
   </ISO_3166-1_Entry>
</ISO_3166-1_List_en>

and the reader is really basic but quick

 XmlTextReader reader = new XmlTextReader("c:/countryCodes.xml");
      List<Country> countriesList = new List<Country>();
      Country country=new Country();
      bool first = false;
      while (reader.Read())
      {
        switch (reader.NodeType)
        {
          case XmlNodeType.Element: // The node is an element.
            if (reader.Name == "ISO_3166-1_Entry") country = new Country();
            break;
          case XmlNodeType.Text: //Display the text in each element.
            if (first == false)
            {
              first = true;
              country.Name = reader.Value;
            }
            else
            {
              country.Code = reader.Value;
              countriesList.Add(country);
              first = false;
            }                       
            break;          
        }        
      }
      return countriesList;  
+1
source

All Articles