开发者

C#: Null reference exception thrown while using XmlDocment

开发者 https://www.devze.com 2023-01-20 22:24 出处:网络
A NullReferenceException is thrown by the runtime when I convert XElement into XmlNode using the following function:

A NullReferenceException is thrown by the runtime when I convert XElement into XmlNode using the following function:

public static XmlNode GetXmlNode(this XElement element)
{
    using (XmlReader xmlReader = element.CreateReader())
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(xmlReader);
        xmlDoc.ChildNodes[4].InnerXml = "0.15"; ====> null reference exception occurs here
        return xmlDoc开发者_JAVA技巧;
    }
}

How can I convert XElement to XmlNode without this problem?


Access the DocumentElement first in order to get the root:

xmlDoc.DocumentElement.ChildNodes[4].InnerXml = "0.15";

EDIT: an XmlDocument inherits from XmlNode. You should be able to simply do this:

XmlNode node = xmlDoc.DocumentElement;
return node;

If you need to cast it for a particular method you could use (XmlNode)xmlDoc.DocumentElement or xmlDoc.DocumentElement as XmlNode.

0

精彩评论

暂无评论...
验证码 换一张
取 消