Document Tree and Nodes
Overview
This guide shows how to walk the node tree of a Word document, find nodes with getChildNodes and remove, clone and append them in Java with Aspose.Words FOSS for Java. A Word document is a tree of nodes. A Document contains Section nodes, a section contains a Body, a body contains paragraphs and tables, and a paragraph contains runs. Every node has a type from NodeType and a text; nodes inside the tree also have a parent and siblings. The nodes that can contain other nodes are CompositeNode objects. getChildNodes(nodeType, isDeep) finds all the nodes of one type below a node, with or without descending into the children. The examples below were compiled and run on Java 8, 17 and 21 with identical output.
Prerequisites
| Requirement | Detail |
|---|---|
| Java | 8 or later |
| Dependency | The package from Installation |
| Import | import com.aspose.words.*; |
| Code | The examples are statements. Put them in a method that declares throws Exception. |
Walk the Tree
Write three paragraphs with a DocumentBuilder, then read the tree from the top: getSections(), the Body of the first section, its getParagraphs() and the runs of each paragraph. The program printed 1 section and 3 paragraphs in the body. The third paragraph had 2 runs because the example wrote it with two write calls, and getChildNodes(NodeType.RUN, true) found 4 runs in the whole document. NodeType.getName turns the type number of a node into its name: the first child of the body was a PARAGRAPH, it is composite, its parent was a BODY and its next sibling was a PARAGRAPH.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("First paragraph");
builder.writeln("Second paragraph");
builder.write("Third ");
builder.write("paragraph");
System.out.println("Sections: " + doc.getSections().getCount());
Body body = doc.getFirstSection().getBody();
System.out.println("Paragraphs in the body: " + body.getParagraphs().getCount());
for (int i = 0; i < body.getParagraphs().getCount(); i++) {
Paragraph paragraph = body.getParagraphs().get(i);
System.out.println(i + ": " + paragraph.getRuns().getCount() + " run(s), text \"" + paragraph.getText().trim() + "\"");
}
NodeCollection runs = doc.getChildNodes(NodeType.RUN, true);
System.out.println("Runs in the whole document: " + runs.getCount());
Node first = body.getFirstChild();
System.out.println("First child of the body is a " + NodeType.getName(first.getNodeType()));
System.out.println("It is composite: " + first.isComposite());
System.out.println("Its parent is a " + NodeType.getName(first.getParentNode().getNodeType()));
System.out.println("Next sibling is a " + NodeType.getName(first.getNextSibling().getNodeType()));The program printed:
Sections: 1
Paragraphs in the body: 3
0: 1 run(s), text "First paragraph"
1: 1 run(s), text "Second paragraph"
2: 2 run(s), text "Third paragraph"
Runs in the whole document: 4
First child of the body is a PARAGRAPH
It is composite: true
Its parent is a BODY
Next sibling is a PARAGRAPHRemove, Clone and Append Nodes
Node.remove() takes a node out of its parent. deepClone(true) copies a node with its children, and appendChild adds a node as the last child of a composite node. The example removed the second paragraph (3 paragraphs remained), appended a clone of the first one (4 paragraphs) and then listed the paragraph texts. Index 2 is the empty paragraph that a new Document already contains and that stays after the last writeln. After saving and reloading, the document had the same 4 paragraphs.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Keep this paragraph");
builder.writeln("Remove this paragraph");
builder.writeln("Keep this one too");
Body body = doc.getFirstSection().getBody();
Paragraph second = body.getParagraphs().get(1);
second.remove();
System.out.println("After remove: " + body.getParagraphs().getCount() + " paragraphs");
Paragraph copy = (Paragraph) body.getParagraphs().get(0).deepClone(true);
body.appendChild(copy);
System.out.println("After appendChild(deepClone): " + body.getParagraphs().getCount() + " paragraphs");
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);
for (int i = 0; i < paragraphs.getCount(); i++) {
System.out.println(i + ": " + paragraphs.get(i).getText().trim());
}
doc.save("tree.docx");
Document reloaded = new Document("tree.docx");
System.out.println("Reloaded paragraphs: " + reloaded.getChildNodes(NodeType.PARAGRAPH, true).getCount());The program printed:
After remove: 3 paragraphs
After appendChild(deepClone): 4 paragraphs
0: Keep this paragraph
1: Keep this one too
2:
3: Keep this paragraph
Reloaded paragraphs: 4Tips and Best Practices
getChildNodesreturns a live collection. In a test with 3writelncalls, a collection of paragraphs reported 4 (the empty last paragraph is counted) and the same collection object reported 3 after one of its paragraphs was removed, so copy the nodes to a list first if you remove them in a loop.- Pass
NodeType.ANYto get nodes of every type. In the same testgetChildNodes(NodeType.ANY, false)on the body returned 3 nodes after one paragraph was removed. getNextSibling()returns null after the last child, so check for null when you walk siblings. In the test it printed null for the last child of the body.Document.getText()ends with a form feed character (code 12) in the test, so usetrim()or strip control characters before you compare or print it.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
| The compiler reports cannot find symbol for Document. | The com.aspose.words package is not imported. | Add import com.aspose.words.*;. |
| The compiler reports an unreported exception. | The Document constructors, Document.save and some other methods declare throws Exception. | Declare it on the calling method or catch it. |
A loop over getChildNodes(...) that removes nodes can skip some of them. | The collection is live, so its indexes change when a node is removed. | Copy the nodes into an ArrayList first, or loop from the last index to the first. |
getNextSibling() returns null. | In the test the node was the last child of its parent. | Test for null before you use the result. |
The paragraph count is one higher than the number of writeln calls. | A new Document starts with one empty paragraph, which stays after the last paragraph you write. | Skip empty paragraphs or remove the last one if you do not want it. |
FAQ
How do I get all the paragraphs of a document?
Call doc.getChildNodes(NodeType.PARAGRAPH, true) and read the result with an index loop. The first example listed the paragraphs of the body with body.getParagraphs(), which holds the direct children only.
How do I find out what kind of node I have?
Call getNodeType() and pass the number to NodeType.getName, as the first example does. In the test it printed PARAGRAPH and BODY.
Does remove() change the saved file?
In the second example the document had 4 paragraphs after the remove and the append, and the reloaded file had 4 paragraphs too. Only the count was checked.
Which formats were tested?
Only DOCX: the examples save a DOCX file and reload it.
API Reference Summary
| Class / Method | Description |
|---|---|
CompositeNode | Base class for nodes that can contain other nodes. |
Node | Base class for all nodes of a Word document. |
NodeType | Specifies the type of a Word document node. |
CompositeNode.getChildNodes(nodeType, isDeep) | Returns a live collection of child nodes that match the specified type. |
CompositeNode.appendChild(newChild) | Adds the specified node to the end of the list of child nodes for this node. |
CompositeNode.getFirstChild() | Gets the first child of the node. |
Node.getNextSibling() | Gets the node immediately following this node. |
Node.remove() | Removes itself from the parent. |
Body.getParagraphs() | Gets a collection of paragraphs that are immediate children of the story. |