Select all paragraphs in a document without the Header and Footer

Hi,

After performing some MergeFields merging, my document ends up with many carriage returns and empty characters.

I write some lines of code to remove carriage returns if the following line of the current line has no text (ie we have 2 consecutive lines without any text):

            // Remove all carriage returns that have no text
            var paragraphs = document.GetChildElements(true, ElementType.Paragraph).Cast<Paragraph>().ToList();
            for (var i = 0; i <= paragraphs.Count() - 1; i++)
            {
                if (paragraphs[i].Content.CountWords() == 0)
                {
                    // Only remove carriage return if the next paragraph is also empty
                    if (i < paragraphs.Count() - 1 && paragraphs[i + 1].Content.CountWords() == 0)
                    {
                        paragraphs[i].Content.Delete();
                    }
                }
            }

Unfortunately, “ElementType.Paragraph” also includes the document header and footer so if my header includes a logo (picture), it gets removed.

Question: how can I select all the paragraphs except the header and footer?
Thanks.

Are you able to create a small Visual Studio project that reproduces this?
I believe that this can be avoided.

Can you try replacing this:

var paragraphs = document.GetChildElements(true, ElementType.Paragraph).Cast<Paragraph>().ToList();

With this:

var paragraphs = document.Sections.SelectMany(sec => sec.Blocks.OfType<Paragraph>()).ToList();

But again, I think you can solve your issue by handling the mail merging process or by processing the mail merge data source.

Regards,
Mario

Thanks Mario.

Indeed, I am also pretty sure it should work out of the box. Giving you a project is difficult because my project has 4 tables hierarchy related by a “ParentId” column so reproducing is not easy with my data.

I’ll try but in the meantime I’ll test your proposal.

Thanks.