2011-06-07 26 views
3

如何获取XmlNode中的文本?见下:如何在XmlNode中获取文本

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 
} 

而我最终想要做的是prepend“HELP:”到每个节点的文本。

回答

9

最简单的方法很可能会超过迭代节点(使用ChildNodes)的所有直接子和测试每一个的NodeType,看它是否是TextCDATA。不要忘记,可能有多个文本节点。

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

(正如一个供参考,如果你可以使用.NET 3.5,LINQ到XML是一个很多更好使用。)

+0

'ChildNodes'是一个'XmlNodeList',它实现了'IEnumerable'的非泛型版本。因此,您需要在上面的循环中明确说明“child”的类型,即“foreach(node.ChildNodes中的XmlNode子节点)”。 – LeopardSkinPillBoxHat 2015-07-13 03:30:17

+0

@LeopardSkinPillBoxHat:已修复,谢谢。 – 2015-07-13 05:52:17

1

你可以阅读的XMLNode 的InnerText属性读取node.InnerText

+0

在代码中的注释明确地说,OP *不*希望所有子节点内获得级联文本,这就是InnerText所做的。 – 2011-06-07 14:25:09

+0

不是我在找什么。请参阅文档:“获取或设置节点及其所有子节点的**连接**值。” – joe 2011-06-07 14:26:01

3

搜索节点的孩子节点与TextNodeType,并使用该节点的Value属性。

请注意,您还可以使用text()节点类型测试选择带有XPath的文本节点。

1

选中此项

您还可以查看您在写入“读取器”时会得到的选项。

xml文件

<?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> 

和读者很基本,但快

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;