如何在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 }
我最终想要做的是在每个节点的文本中预先添加“HELP:”。
最简单的方法可能是迭代节点的所有直接子节点(使用ChildNodes
)并测试每个节点的NodeType
以查看它是Text
还是CDATA
。 不要忘记可能有多个文本节点。
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 to XML可以使用得更好。)
在节点的子节点中搜索NodeType
为Text
的节点,并使用该节点的Value
属性。
请注意,您还可以使用text()
节点类型测试选择具有XPath的text()
节点。
你可以读取xmlnode读取node.InnerText
的InnerText属性
检查一下
你也可以查看你写“读者”时得到的选项。
xml文件
SINT MAARTEN SX SLOVAKIA SK
读者真的很基本但很快
XmlTextReader reader = new XmlTextReader("c:/countryCodes.xml"); List countriesList = new List (); 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;