XmlNode中Value和InnerText的区别
XmlNode中Value和InnerText的区别
这个问题我想很多人在使用.NET 操作 Xml 文档时都遇到过,先看一下MSDN里对这两个属性的解释:
XmlNode.Value:获取或设置节点的值。
XmlNode.InnerText:获取或设置节点及其所有子节点的串联值。
只看这两个定义是不是还是有点迷糊,下面我们用实例来作说明:
1.当操作节点是叶子节点时:
XmlDocument xDoc=new XmlDocument();
xDoc.LoadXml(@"<SmartCoder>
<Coder>
<Name>Tiramisu</Name>
<Age>25</Age>
</Coder>
</SmartCoder>");
XmlNode root=xDoc.DocumentElement;
XmlNode nameNode=root.SelectSingleNode("Coder/Name"); // 获取Name节点
Console.WriteLine(nameNode.Value);
Console.WriteLine(nameNode.InnerText);
输出结果如下:
null
Tiramisu
2.当操作节点是父结点时:
XmlDocument xDoc=new XmlDocument();
xDoc.LoadXml(@"<SmartCoder>
<Coder>
<Name>Tiramisu</Name>
<Age>25</Age>
</Coder>
</SmartCoder>");
XmlNode root=xDoc.DocumentElement;
XmlNode coderNode=root.SelectSingleNode("Coder"); // 获取Name节点
Console.WriteLine(coderNode.Value);
Console.WriteLine(coderNode.InnerText);
输出结果如下:
null
Tiramisu25
3.当操作节点是属性时:
XmlDocument xDoc=new XmlDocument();
xDoc.LoadXml(@"<SmartCoder>
<Coder EnglishName='Benjamin'>
<Name>Tiramisu</Name>
<Age>25</Age>
</Coder>
</SmartCoder>");
XmlNode root=xDoc.DocumentElement;
XmlNode coderNode=root.SelectSingleNode("Coder"); // 获取Name节点
Console.WriteLine(coderNode.Attributes["EnglishName"].Value);
Console.WriteLine(coderNode.Attributes["EnglishName"].InnerText);
或
XmlDocument xDoc=new XmlDocument();
xDoc.LoadXml(@"<SmartCoder>
<Coder EnglishName='Benjamin'>
<Name>Tiramisu</Name>
<Age>25</Age>
</Coder>
</SmartCoder>");
XmlNode root=xDoc.DocumentElement;
XmlNode engNameAttr=root.SelectSingleNode("Coder/@EnglishName"); // 获取Name节点
Console.WriteLine(engNameAttr.Value);
Console.WriteLine(engNameAttr.InnerText);
输出结果:
Benjamin
Benjamin
上文的示例代码中,我们使用了XPath语法来查找DOM元素,更多的XPath语法信息,大家请自行查阅。
从示例中我们可以看出,InnerText会把节点及其子元素的文本内容(尖括号所包含的内容)拼接起来作为返回值;而Value则不然,无论是父节点还是子节点,返回值都为 null ,而当操作的节点类型为属性时,Value的返回值与InnerText相同。其实,Value的返回值,与节点类型(NodeType)相关,下面是MSDN中列出的节点类型及 XmlNode.Value 的返回值:
类型 | 值 |
Attribute | 属性的值 |
CDATASection | CDATA 节的内容。 |
Comment | 注释的内容 |
Document | null |
DocumentFragment | null |
DocumentType | null |
Element | null . 您可以使用 XmlElement.InnerText 或 XmlElement.InnerXml 属性访问元素节点的值。 |
Entity | null |
EntityReference | null |
Notation | null |
ProcessingInstruction | 全部内容(不包括指令目标)。 |
Text | 文本节点的内容 |
SignificantWhitespace | 空白字符。 空白可由一个或多个空格字符、回车符、换行符或制表符组成。 |
Whitespace | 空白字符。 空白可由一个或多个空格字符、回车符、换行符或制表符组成。 |
XmlDeclaration | 声明的内容(即在 <?xml 和 ?> 之间的所有内容)。 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)