這個問題我想很多人在使用.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 和 ?> 之間的所有內容)。 |