Search code examples
c#openxml

Find a specific Table (after a bookmark) in open xml


I have a document with multiple tables in it. I need to fill some of those tables. The problem im having is how do i locate them? I can interate through them

var doc = document.MainDocumentPart.Document;
var tables= doc.Body.Elements< Table >();

But how do i find a specific table? The table can change so i cant rely on the order. I was thinking of placing a bookmark ahead of the specific table and just locate the first table after the bookmark, but i have failed to find out how to do that...

So, how do one find a specific table in a document?

If there is a better way of doing it please let me know.


Solution

  • Give the tables captions.

    First in Word, create the tables, and right click one of them, Table Properties, Alt Text, fill in the Title box, save, close.

    Now in OpenXML, find the table with specific captions.

    IEnumerable<TableProperties> tableProperties = bd.Descendants<TableProperties>().Where(tp => tp.TableCaption != null);
    foreach(TableProperties tProp in tableProperties)
    {
        if(tProp.TableCaption.Val.Equals("myCaption")) // see comment, this is actually StringValue
        {
            // do something for table with myCaption
            Table table = (Table) tProp.Parent;
        }
    }