1

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;
    }
}

How can I convert XElement to XmlNode without this problem?

3
  • Does ChildNodes (an XmlNodeList) throw an index out of range exception or return null when you try to access a node that does not exist? Are you sure the node you are trying to change exists? Commented Oct 21, 2010 at 4:31
  • it exists it doesit throw exception Commented Oct 21, 2010 at 4:33
  • i like to convertXelement into xmlnode Commented Oct 21, 2010 at 4:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

how can i convert it into XMLNode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.