It is important to mention that a node always belongs to a particular document, even if it was just created or has been removed from the tree. The document to which the node belongs is returned by the Node.Document property.
A node always belongs to a document, because some vital document-wide structures such as styles and lists are stored in the Document node. For example, it is not possible to have a Paragraph without a Document because each paragraph has a style assigned to it and the style is defined globally for the document.
Example CreatingNodeRequiresDocument
Shows that when you create any node, it requires a document that will own the node.
[C#]
// Open a file from disk.
Document doc = new Document();
// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);
// The new paragraph node does not yet have a parent.
Assert.IsNull(para.ParentNode);
// But the paragraph node knows its document.
Assert.AreEqual(doc, para.Document);
// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.ParagraphFormat.StyleName = "Heading 1";
// Now add the paragaph to the main text of the first section.
doc.FirstSection.Body.AppendChild(para);
// The paragraph node is now a child of the Body node.
Assert.IsNotNull(para.ParentNode);
[Visual Basic]
' Open a file from disk.
Dim doc As Document = New Document()
' Creating a new node of any type requires a document passed into the constructor.
Dim para As Paragraph = New Paragraph(doc)
' The new paragraph node does not yet have a parent.
Assert.IsNull(para.ParentNode)
' But the paragraph node knows its document.
Assert.AreEqual(doc, para.Document)
' The fact that a node always belongs to a document allows us to access and modify
' properties that reference the document-wide data such as styles or lists.
para.ParagraphFormat.StyleName = "Heading 1"
' Now add the paragaph to the main text of the first section.
doc.FirstSection.Body.AppendChild(para)
' The paragraph node is now a child of the Body node.
Assert.IsNotNull(para.ParentNode)
[Java]
// Open a file from disk.
Document doc = new Document();
// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);
// The new paragraph node does not yet have a parent.
Assert.assertNull(para.getParentNode());
// But the paragraph node knows its document.
Assert.assertEquals(doc, para.getDocument());
// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.getParagraphFormat().setStyleName("Heading 1");
// Now add the paragaph to the main text of the first section.
doc.getFirstSection().getBody().appendChild(para);
// The paragraph node is now a child of the Body node.
Assert.assertNotNull(para.getParentNode());