Find a Word check box control by its Tag property using Open XML SDK

2.1k views Asked by At

I have a Word 2013 document containing a check box control. I have set this checkbox's Tag property to fooCheckBox:

Screenshot showing a Word 2013 checkbox's properties

Now I would like to programmatically find and manipulate that particular checkbox using Open XML SDK 2.5. I know how to find/enumerate checkboxes, but I don't know how to find a particular SdtContentCheckBox by its Tag property:

Given a WordprocessingDocument doc, how can I retrieve a specific SdtContentCheckBox's by its Tag property?

(I have working code, which I am posting as an answer (see below). However, I have no idea if this is the right way to do it; so if someone knows a better, more proper way, I'd like to see how it's done.)

1

There are 1 answers

0
stakx - no longer contributing On BEST ANSWER

Apparently, a SdtContentCheckBox object's .Parent property references a SdtProperty collection which can be queried for a Tag descendant.

I do not understand the logic behind this object modelling, but it can be used to get the job done:

// using DocumentFormat.OpenXml.Packaging;
// using System.Diagnostics;
// using System.Linq;

SdtContentCheckBox TryGetCheckBoxByTag(WordprocessingDocument doc, string tag)
{
    foreach (var checkBox in doc.MainDocumentPart.Document.Descendants<SdtContentCheckBox>())
    {
        var tagProperty = checkBox.Parent.Descendants<Tag>().FirstOrDefault();
        if (tagProperty != null)
        {
            Debug.Assert(tagProperty.Val != null);
            if (tagProperty.Val.Value == tag)
            {
                // a checkbox with the given tag property was found
                return checkBox;
            }
        }
    }
    // no checkbox with the given tag property was found
    return null;
}