There is a truly recursive call.
pDoc.Save() calls WriteTo(XmlWriter w) in the document, which calls WriteContentTo(XmlWriter w) .
Then it calls WriteTo(XmlWriter w) on all nodes of the root level, which will contain one node element (maybe also some comments, spaces, processing instructions, document declaration ...).
In this element, this will cause it to write its tag ('<', the name of the element, and then any attributes), and then call WriteContentTo(XmlWriter w) , which calls WriteTo(XmlWriter w) for each child element that calls WriteContentTo(XmlWriter w) , etc. etc.
Therefore, this is really recursive in the way each element calls the same method for its children and with a sufficiently deep document on a fairly small stack space (by default, most applications use 1 MB, but 256 KB on ASP.NET) Overflow stack.
For the record, you can also have stack overflow without recursion if you somehow drive the stack space. stackalloc is a great way to find yourself by making just a few calls.
If you are having problems due to this recursion, remember that the WriteTo implementation is essentially (manually inserting WriteContentTo into it):
w.WriteStartElement(this.Prefix, this.LocalName, this.NamespaceURI); if (this.HasAttributes) { XmlAttributeCollection attributes = this.Attributes; for (int i = 0; i < attributes.Count; i++) { attributes[i].WriteTo(w); } } if (this.IsEmpty) { w.WriteEndElement(); } else { for (XmlNode node = this.FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } w.WriteFullEndElement(); }
Replace it with the iterative version and you won’t overflow the stack. Of course, if you managed to somehow bring the document to a state where it received an element that is an ancestor of itself (does XmlDocument protect against this? I don’t know, from my point of view), then it will turn the stack overflow into an infinite loop, which if something is worse.