OpenXML - counting paragraphs in a document with altChunk elements

Viewed 324

I am trying to count the number of paragraphs or runs in a Word document using OpenXML. For a simple document this can be accomplished this way:

using (WordprocessingDocument document = WordprocessingDocument.Open(file, false))
{                  
    var paragraphs = document.MainDocumentPart.Document.Body.
       Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();

    int numberOfParagraphs  = paragraphs.ToArray().Length;

    var runs = document.MainDocumentPart.Document.Body.
        Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>();
    
    int numberOfRuns  = runs.ToArray().Length;
}

But I run into trouble with documents that have been created from merging small documents using AltChunks. The values returned are wrong and way too low. So I presume that I am missing all or some of the paragraphs or runs in the chunks.

Any ideas for how to count the paragraph or run elements in an AltChunk? I tried looking at descendants in each AltChunk, but I get 0's.

I have an idea that I'd be able to count if I convert each AltChunk to a document, but the WordprocessingDocument.Open method doesn't work when I pass it an AltChunk.

Any ideas would be appreciated.

1 Answers

The mainDocumentPart will hold all the original paragraphs and the altChunks. You need to iterate over the altChunks to know how many paragraphs each altChunk has.

The following code works for me:

static void Main(string[] args)
{
    string fileName1 = @"Destination.docx";
    string fileName2 = @"Source.docx";
    string testFile = @"Test.docx";
    File.Delete(fileName1);
    File.Copy(testFile, fileName1);
    using (WordprocessingDocument myDoc =
        WordprocessingDocument.Open(fileName1, true))
    {
        string altChunkId = "AltChunkId1";
        MainDocumentPart mainPart = myDoc.MainDocumentPart;
        AlternativeFormatImportPart chunk =
            mainPart.AddAlternativeFormatImportPart(
            AlternativeFormatImportPartType.WordprocessingML, altChunkId);
        using (FileStream fileStream = File.Open(fileName2, FileMode.Open))
            chunk.FeedData(fileStream);
        AltChunk altChunk = new AltChunk();
        altChunk.Id = altChunkId;
        mainPart.Document
            .Body
            .InsertAfter(altChunk, mainPart.Document.Body
            .Elements<Paragraph>().Last());
        mainPart.Document.Save();

        // Counting paragraphs

        int paragraphCount = 0;

        paragraphCount += mainPart.Document.Body.Elements<Paragraph>().Count();
        var altChunks = mainPart.Document.Body.Descendants<AltChunk>().ToList();
        foreach (var aChunk in altChunks)
        {
            paragraphCount += aChunk.Parent.Elements<Paragraph>().Count();
        }

        Console.WriteLine("Paragraph Count:: {0}", paragraphCount);
        Console.ReadLine();
    }
}
Related