Get Table After insertHtml

If I insert an html table or multiple tables after moving to a bookmark, how would I get the table so that I could apply an additional style or formatting to it? Is there any way to get to the table by a particular id or style so that I know I’m formatting the proper table if there are multiples?

documentBuilder.moveToBookmark(bookmarkName)
documentBuilder.insertHtml(htmlText)
documentBuilder.getCurrentParagraph()

-Thanks

Hi
Thanks for your request. You can get any of table using an index of a table collection:

// Get collection of tables
NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);
// Get table by table index
Table myTable = (Table) tables.get(1);

Also you can try putting some bookmark inside the table and then get this table using the following code:

// Open document.
Document doc = new Document("in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Move DocumentBuilder cursor to the bookmark.
builder.moveToBookmark("myBk");
// Get Table, where bookmark is located.
Table myTable = (Table) builder.getCurrentParagraph().getAncestor(NodeType.TABLE);

Or you can try using getting the immediate parent of current node:
https://reference.aspose.com/words/java/com.aspose.words/node/#getParentNode
Best regards,

I can get the table inserted at the bookmark with:

documentBuilder.moveToBookmark("myBk")

documentBuilder.getCurrentParagraph().getPreviousSibling()

I’d like to be able to get a nodeCollection of 1 or more tables that I may have inserted at the bookmark via insertHtml so that I can loop over them.

But I’m not having any luck with:

documentBuilder.getCurrentParagraph().getAncestor(NodeType.TABLE)

Thanks

Hi there,
Thanks for your inquiry.
Please try using the method in the code below instead. This will return an List of nodes inserted during the InsertHtml call.

List<Node> newNodes = InsertHtmlAndReturnNewNodes(builder, "<table><tr><td>Test Table</td></tr></table>");
for(Node node : newNodes)
{
   if(node.getNodeType() == NodeType.TABLE)
       ((Table)node).setStyleIdentifier(StyleIdentifier.MEDIUM_GRID_1_ACCENT_1);
}

public static List<Node> InsertHtmlAndReturnNewNodes(DocumentBuilder builder, String html) throws Exception
{
    List<Node> startingNodes = Arrays.asList(builder.getDocument().getChildNodes(NodeType.ANY, true).toArray());
    builder.insertHtml(html);
    List<Node> endingNodes = Arrays.asList(builder.getDocument().getChildNodes(NodeType.ANY, true).toArray());
    endingNodes.removeAll(startingNodes);

    return endingNodes;
}

Hopefully this helps. If you have any other queries, please feel free to ask.
Thanks,