How to get text inside an XmlNode

▼魔方 西西 提交于 2019-12-01 18:43:46

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

Search the node's children for a node with NodeType of Text, and use the Value property of that node.

Note that you can also select text nodes with XPath by using the text() node-type test.

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

Check this

also you might check what options 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 reader really basic but fast

 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;  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!