如何在XmlNode中获取文本 [英] How to get text inside an XmlNode

查看:55
本文介绍了如何在XmlNode中获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

我最终想要做的是在每个节点的文本前添加"HELP:".

And what I ultimately want to do is preppend "HELP: " to the text in each node.

推荐答案

最简单的方法可能是遍历节点的所有直接子节点(使用 ChildNodes )并测试每个节点的NodeType ,以查看它是 Text 还是 CDATA .不要忘记可能有多个文本节点.

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

(就像FYI一样,如果您可以使用.NET 3.5,则LINQ to XML是更易于使用的 .)

(Just as an FYI, if you can use .NET 3.5, LINQ to XML is a lot nicer to use.)

这篇关于如何在XmlNode中获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆