Hi Team,
I am trying to remove a table and replace a Mergefield there at the sama position where the table was present.
Here is the below sample code,
String filePathSDT = "C:\\Users\\wb541348\\Project\\TestDoc.docx";
InputStream instreamSDT =new FileInputStream(filePathSDT);
Document doc = new Document(filePathSDT);
DocumentBuilder builder = new DocumentBuilder(doc);
NodeCollection<Table> tablenodes = doc.getChildNodes(NodeType.TABLE, true);
for(Table table : tablenodes) {
builder.moveTo(table.getPreviousSibling());
table.remove();
builder.insertField("MERGEFIELD " + "Test" + " \\* MERGEFORMAT");
}
doc.save("C:\\Users\\wb541348\\Project\\Result.docx");
Above code executes properly at times , and it fails at times with Null pointer exception at builder.moveTo(table.getPreviousSibling());
Please let me know how to handle them, What if I dint have a previous sibling and How should I remove the table and replace a MergeField there in those cases.
I mean, I need to remove the table and place a Mergefield exactly at the same position where I removed the Table.
As there is a section break before the table. I am getting a Null pointer exception for the below,
Table.getPreviousSibling();
Basically, I want to move the cursor before the table , and I am not able to do it as there are no node before the table except for a section break. Please find below screenshot.
image.png (3.4 KB)
Thanks,
Prasanna Shanmuganathan