This project has moved and is read-only. For the latest updates, please go here.

Hack: Added Container.InsertParagraphAfter

Feb 24, 2015 at 2:39 PM
Edited Feb 24, 2015 at 3:46 PM
Hi,
if I got everything correctly, DocX is currently best suited to create documents from scratch or append data to existing ones, right? Manipulation is only supported on (string) replacement level.

I wanted to be able to jump to a bookmark and add paragraphs after the bookmark's paragraph, so I added the following method to Container.cs:
        public virtual Paragraph InsertParagraphAfter(Paragraph precedingParagraph, string text, bool trackChanges, Formatting formatting)
        {
            XElement newParagraph = new XElement
            (
                XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
            );

            if (trackChanges)
                newParagraph = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraph);

            const string attributeName = "documentInternalId";
            var documentInternalId = Guid.NewGuid();
            
            newParagraph.SetAttributeValue(attributeName, documentInternalId);
            precedingParagraph.Xml.AddAfterSelf(newParagraph);
            
            var paragraphAdded = (from p in Paragraphs
                                  where documentInternalId.ToString().Equals(p.Xml.GetAttribute(attributeName))
                select p).Single();

            GetParent(paragraphAdded);

            return paragraphAdded;
        }
I had to add the ugly documentInternalId to be able to find the paragraph again. :-(
So it's not really a nice solution, but as far as I can tell, a better solution would need some refactoring the DocX codebase.

If someone has a more elegant solution, I would be glad to hear it.

BTW: If modification support gets implemented, perhaps the following might be useful as an example of a cursor model and serve as inspiraton: The XPathNavigator "provides a cursor model for navigating and editing XML data".