How do I get the XML root node with C#?
Root node is the DocumentElement
property of XmlDocument
XmlElement root = xmlDoc.DocumentElement
If you only have the node, you can get the root node by
XmlElement root = xmlNode.OwnerDocument.DocumentElement
I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.
using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
while (reader.Read()) {
// first element is the root element
if (reader.NodeType == XmlNodeType.Element) {
System.Console.WriteLine(reader.Name);
break;
}
}
}