What is the equivalent of VBA's SelectContentControlsByTag() in OpenXML SDK for Word files? RRS feed

  • Question

  • In this article I saw a cool function - SelectContentControlsByTag (). But its implementation in C# mentioned below in the article doesn't find my ContentControl always. In the DOCX located here it can't find by tag "QWERTY1". The quistion is if there any analog of this VBA's function?
    Thursday, March 29, 2012 9:12 AM


  • Hi Senglory,

    Thanks for posting in the MSDN Forum.

    I hope following snippet can help you.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    namespace ConsoleApplication6
        class Program
            static void Main(string[] args)
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;
                dialog.Filter = "Word Document|*.docx";
                string path = dialog.FileName;
                using (WordprocessingDocument wd = WordprocessingDocument.Open(path, true))
                    MainDocumentPart mp = wd.MainDocumentPart;
                    Document d = mp.Document;
                    SdtBlock sb = d.Descendants<SdtBlock>().Where(B => B
                        .SdtProperties.GetFirstChild<Tag>().Val == "QWERTY1")
                    Paragraph p = sb.SdtContentBlock.GetFirstChild<Paragraph>();
                    Run r = p.GetFirstChild<Run>();
                    Text t = r.GetFirstChild<Text>();
                    t.Text = "This is I want";

    Have a good day,


    Tom Xu [MSFT]
    MSDN Community Support | Feedback to us

    Monday, April 2, 2012 9:15 AM