XmlNode Value vs InnerText

后端 未结 5 2031
梦毁少年i
梦毁少年i 2020-12-08 18:03

I\'m creating a ping application for school with an XML full of URLs. I lost an hour because of XmlNode.Value was resulting in a null.

Then I changed i

相关标签:
5条回答
  • 2020-12-08 18:37

    I had a similar situation. What I did is, I picked the first child of the current node and checked if it is XMLtext, then displayed its value.

    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");
        }
    }
    
    0 讨论(0)
  • 2020-12-08 18:40

    The XML specification is very picky about terminology and what constitutes what type of XML object. As mentioned, element doesn't have a value. This is specific to attribute (and probably a couple of other node types) because attribute has a syntax that element does not, i.e. name='value'.

    If you think that's confusing, check out the difference between child and descendant, or the Root Node and the Document Element!

    0 讨论(0)
  • 2020-12-08 18:41

    If, for example, your XML looks like <Foo>Bar</Foo> then "Bar" is actually considered a separate node: an XmlText node (sub-classed from XmlNode). The Value property of that XmlText node would be "Bar".

    "Foo" is considered to be an XmlElement (also sub-classed from XmlNode). XmlNode.Value returns different things based on the type of node it is. See this table which shows that Value always returns null for Element nodes.

    The InnerText of the Foo node returns "Bar" because it concatenates the values of its children (in this case, only the one XmlText node).

    0 讨论(0)
  • 2020-12-08 18:45

    As url element is the leaf node, the InnerText(also InnerXml) property contains the element value. For element nodes, the value property will be null as shown in msdn documentation https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.value(v=VS.110).aspx.

    0 讨论(0)
  • 2020-12-08 18:55

    Regarding to MSDN, Value property of XmlNodeType.Element returns:

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

    0 讨论(0)
提交回复
热议问题