Remove field and it's containing paragraph and insert a new paragraph in their place?

I have a problem modifying an existing document. I find a field that I want to remove and remove it:

Node node = field.remove();

The node is now the paragraph that contained the field. I remove it with node.remove().

But now I need to insert a new paragraph or other block content at the location of the old node just removed. I have tried many ways with DocumentBuilder to set the cursor with moveTo() and other appends but have been unable to find the right combination.

I know this must be straightforward but I’m at a bit of a loss. Any help would be greatly appreciated!

@mitchhayes Field.remove() method not always returns a paragraph. It returns a node right after the field. If the field’s end is the last child of its parent node, returns its parent paragraph. If the field is already removed, returns null . So you can use code like the following to remove content from the paragraph with the field and insert new content instead:

Document doc = new Document("C:\\Temp\\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

// Get some field
Field field = doc.getRange().getFields().get(0);

// Remove the field
Node node = field.remove();
Paragraph fieldParentParagraph;
// Paragraph node is returned if the field is the last child of the paragraph.
if (node.getNodeType() == NodeType.PARAGRAPH)
    fieldParentParagraph = (Paragraph)node;
else
    fieldParentParagraph = (Paragraph)node.getAncestor(NodeType.PARAGRAPH);

// Remove all paragraphs children
fieldParentParagraph.removeAllChildren();
// Move cursor into the empty paragraph.
builder.moveTo(fieldParentParagraph);

// Now we can insert new content.
builder.write("This is new content");

doc.save("C:\\Temp\\out.docx");

Thanks Alexey! That was just what I needed. I didn’t catch the different nodes that could be returned from the remove nor the use of getAncestor().

1 Like