从文档中,XmlElement.InnerText
获取或设置节点及其所有子节点的串联值。
虽然这个陈述并不完全清楚,但它暗示该属性下降到元素下的 DOM 层次结构,并将所有文本值连接到返回值中——您所看到的行为。
扩展接受的答案,这里是从参考源改编的扩展方法,收集并返回给定节点的所有直接文本子节点:
public static partial class XmlNodeExtensions
{
/// <summary>
/// Returns all immediate text values of the given node, concatenated into a string
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static string SelfInnerText(this XmlNode node)
{
// Adapted from http://referencesource.microsoft.com/#System.Xml/System/Xml/Dom/XmlNode.cs,66df5d2e6b0bf5ae,references
if (node == null)
return null;
else if (node is XmlProcessingInstruction || node is XmlDeclaration || node is XmlCharacterData)
{
// These are overridden in the reference source.
return node.InnerText;
}
else
{
var firstChild = node.FirstChild;
if (firstChild == null)
return string.Empty;
else if (firstChild.IsNonCommentText() && firstChild.NextSibling == null)
return firstChild.InnerText; // Optimization.
var builder = new StringBuilder();
for (var child = firstChild; child != null; child = child.NextSibling)
{
if (child.IsNonCommentText())
builder.Append(child.InnerText);
}
return builder.ToString();
}
}
/// <summary>
/// Enumerates all immediate text values of the given node.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static IEnumerable<string> SelfInnerTexts(this XmlNode node)
{
// Adapted from http://referencesource.microsoft.com/#System.Xml/System/Xml/Dom/XmlNode.cs,66df5d2e6b0bf5ae,references
if (node == null)
yield break;
else if (node is XmlProcessingInstruction || node is XmlDeclaration || node is XmlCharacterData)
{
// These are overridden in the reference source.
yield return node.InnerText;
}
else
{
var firstChild = node.FirstChild;
for (var child = firstChild; child != null; child = child.NextSibling)
{
if (child.IsNonCommentText())
yield return child.InnerText;
}
}
}
public static bool IsNonCommentText(this XmlNode node)
{
return node != null &&
(node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA
|| node.NodeType == XmlNodeType.Whitespace || node.NodeType == XmlNodeType.SignificantWhitespace);
}
}
然后像这样使用它:
var value = XMLMNode.SelfInnerText();
样品小提琴。