Search code examples
ms-wordopenxmlword-2007wordprocessingml

Tag spot in word document


How can I tag a "spot" (this can be a text area or text field) in a word document? I tried putting a plain text content control in my document, but when I looked at the generated XML there was no "alias" for that plain text control. All the code I've seen for getting one, needs it to have an alias. What am I doing wrong? And is there another easier way to easily "mark" a spot in a document and retrieve the text that's in it later? (The user will be entering the text...)


Solution

  • In Visual Studio I was able to use the designer to set the properties of the plain text control. On the properties there is a "tag" property that I set to the name I wanted for my tag. Then using this method I was able to find the control later:

    WordprocessingDocument document = WordprocessingDocument.Open(file.OpenBinaryStream(), true);
    
            var docPart = document.MainDocumentPart;
            // Find the first content control whose Alias property
            // matches the supplied name.
            var sdts = docPart.Document.Descendants<Tag>();
            foreach (var sdt in sdts)
            {
                string value = (string)sdt.Val;
    
                if (value.Equals(contentControlTag))
                {
                    oxe = sdt;
                    break;
                }
            }
    
            return oxe;