How to get text inside an XmlNode

2019-02-24 09:25发布

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.

4条回答
趁早两清
2楼-- · 2019-02-24 09:54

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;  
查看更多
乱世女痞
3楼-- · 2019-02-24 10:12

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.

查看更多
仙女界的扛把子
4楼-- · 2019-02-24 10:17

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

查看更多
聊天终结者
5楼-- · 2019-02-24 10:18

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

查看更多
登录 后发表回答