NodeGetAncestor Method (Type) |
Namespace: Aspose.Words
The ancestor type matches if it is equal to ancestorType or derived from ancestorType.
public void CalculateDepthOfNestedTables() { Document doc = new Document(MyDir + "Nested tables.docx"); int tableIndex = 0; foreach (Table table in doc.GetChildNodes(NodeType.Table, true).OfType<Table>()) { // First lets find if any cells in the table have tables themselves as children int count = GetChildTableCount(table); Console.WriteLine("Table #{0} has {1} tables directly within its cells", tableIndex, count); // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth int tableDepth = GetNestedDepthOfTable(table); if (tableDepth > 0) Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", tableIndex, tableDepth); else Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", tableIndex); tableIndex++; } } /// <summary> /// Calculates what level a table is nested inside other tables. /// <returns> /// An integer containing the level the table is nested at. /// 0 = Table is not nested inside any other table /// 1 = Table is nested within one parent table /// 2 = Table is nested within two parent tables etc..</returns> /// </summary> private static int GetNestedDepthOfTable(Table table) { int depth = 0; // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table Node parent = table.GetAncestor(table.NodeType); while (parent != null) { // Every time we find a table a level up we increase the depth counter and then try to find an // ancestor of type table from the parent depth++; parent = parent.GetAncestor(typeof(Table)); } return depth; } /// <summary> /// Determines if a table contains any immediate child table within its cells. /// Does not recursively traverse through those tables to check for further tables. /// <returns>Returns true if at least one child cell contains a table. /// Returns false if no cells in the table contains a table.</returns> /// </summary> private static int GetChildTableCount(Table table) { int tableCount = 0; // Iterate through all child rows in the table foreach (Row row in table.Rows.OfType<Row>()) { // Iterate through all child cells in the row foreach (Cell Cell in row.Cells.OfType<Cell>()) { // Retrieve the collection of child tables of this cell TableCollection childTables = Cell.Tables; // If this cell has a table as a child then return true if (childTables.Count > 0) tableCount++; } } // No cell contains a table return tableCount; }