关于c#:XmlNode值与InnerText

XmlNode Value vs InnerText

我正在为学校创建一个ping应用程序,该应用程序具有一个充满URL的XML。
我因为XmlNode.Value导致空值而损失了一个小时。

然后我将其更改为InnerText,它工作正常。

现在我不知道有什么区别,因为MSDN说.Value返回节点的值,而InnerText返回节点及其所有子节点的串联值。

有人可以帮我解释一下吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
<sites>
<site>
    <url>www.test.be</url>
    test@test.be</email>
</site>
<site>
    <url>www.temp.be</url>
    temp@temp.be</email>
</site>
<site>
    <url>www.lorim.ipsum</url>
    interim.address@domain.com</email>
</site></sites>


例如,如果您的XML看起来像<Foo>Bar</Foo>,则" Bar "实际上被认为是一个单独的节点:XmlText节点(从XmlNode子类化)。该XmlText节点的Value属性将为" Bar "。

" Foo "被认为是XmlElement(也从XmlNode子类化)。 XmlNode.Value根据其所在的节点类型返回不同的结果。请参阅此表,该表显示Value始终为Element节点返回null

Foo节点的InnerText返回" Bar ",因为它连接了其子级的值(在这种情况下,只有一个XmlText节点)。


我也有类似的情况。我所做的是,我选择了当前节点的第一个子节点,并检查它是否为XMLtext,然后显示其值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
XmlNodeList xNList = xDOC.SelectNodes("//" + XMLElementname);

foreach (XmlNode xNode in xNList)
{
    if (xNode.ChildNodes.Count == 1 &&
        xNode.FirstChild.GetType().ToString() =="System.Xml.XmlText")
    {
        XMLElements.Add(xNode.FirstChild.Value);
    }
    else
    {
        XMLElements.Add("This is not a Leaf node");
    }
}


XML规范对术语以及构成什么类型??的XML对象非常挑剔。如前所述,Element没有值。这特定于attribute(可能还有其他几种节点类型),因为attribute具有Element不具备的语法,即name='value'

如果您认为这令人困惑,请检查子代与子代或根节点和文档元素之间的区别!


由于url元素是叶节点,因此InnerText(也是InnerXml)属性包含元素值。对于元素节点,值属性将为null,如msdn文档https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.value(v=VS.110).aspx.


关于MSDN,XmlNodeType.ElementValue属性返回:

null. You can use the XmlElement.InnerText or XmlElement.InnerXml properties to access the value of the element node.