How to Walk the Node Tree of a Word Document in Java

How to Walk the Node Tree of a Word Document in Java

Aspose.Words FOSS for Java represents a Word document as a tree of nodes: document, sections, body, paragraphs and runs. This guide walks the tree, removes a paragraph and clones another, with the library from Maven Central.

Step-by-Step Guide

Step 1: Install the Package

Add the package to your build. The library needs Java 8 or later.

<dependency>
  <groupId>org.aspose</groupId>
  <artifactId>aspose-words-foss</artifactId>
  <version>26.3.0</version>
</dependency>

Step 2: Import the Classes

All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;. The examples are statements: put them in a method that declares throws Exception.


Step 3: Walk the Sections, Paragraphs and Runs

Open or build a Document, take the Body of the first section and read its paragraphs and their runs. NodeType.getName(node.getNodeType()) gives the name of a node type. The run printed 1 section, 3 paragraphs, 4 runs in the whole document, and a first child of the body that 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 PARAGRAPH

Step 4: Remove and Clone a Paragraph

remove() takes a node out of its parent, deepClone(true) copies it with its children and appendChild adds the copy at the end of the body. The example writes three paragraphs, so the body holds 4 (the three written plus the empty last one). After the removal it held 3 and after the clone 4, and the reloaded file had 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: 4

Common Issues and Fixes

A loop that removes nodes can skip some of them. getChildNodes returns a live collection. In a test its count dropped from 4 to 3 after one removal, so indexes move while you loop. Copy the nodes to a list before you remove them.

getNextSibling returns null. In the test the node was the last child of its parent. Check for null.

There is one empty paragraph more than I wrote. A new Document already contains one empty paragraph and it stays after the last writeln.

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.

Frequently Asked Questions

Is the collection from getChildNodes a copy?

No, it is live. In a test the same collection object reported 4 nodes before a removal and 3 after it.

Does getText add anything at the end?

In a test Document.getText() ended with a form feed character (code 12). Use trim() before you compare it.

See Also