Search code examples
c#ms-wordopenxml

How to retrieve text commented or bookmarked in Microsoft Office Word, with OpenXML


I've been trying for a while to retrieve text that is commented or bookmarked by the user, in the .docx document, using OpenXML. I tried building dictionaries and arrays with the start and end tag of each comments/bookmarks, and tried to navigate through the XML tree nodes, to obtain the text but I'm not obtaining all of it (just the first child, which is the first word).

IDictionary<String, BookmarkStart> bookmarkMapS = new Dictionary<String, BookmarkStart>();

IDictionary<String, BookmarkEnd> bookmarkMapE = new Dictionary<String, BookmarkEnd>();

var _bkms = doc.MainDocumentPart.RootElement.Descendants<BookmarkStart>();
var _bkme = doc.MainDocumentPart.RootElement.Descendants<BookmarkEnd>();

        foreach (BookmarkStart item in _bkms)
        {
            Run bookmarkText = item.NextSibling<Run>();
            if (bookmarkText != null)
            {
                try
                {
                    for (int i = 0; i < bookmarkText.ChildElements.Count(); i++)
                    {
                        Console.WriteLine(bookmarkText.ChildElements.ElementAt(i).InnerText);    
                    }   
                }
                catch (Exception)
                {   
                }   
            }
        }

Solution

  • There is probably a better way to do this, but this is what I came up with.

    List<OpenXmlElement> elems =new List<OpenXmlElement>(doc.MainDocumentPart.Document.Body.Descendants());
    var crs=doc.MainDocumentPart.RootElement.Descendants<CommentRangeStart>();
    var cre=doc.MainDocumentPart.RootElement.Descendants<CommentRangeEnd>();
    var dic_cr=new Dictionary<CommentRangeStart, CommentRangeEnd>();
    for (int i = 0; i < crs.Count(); i++)
    {
        dic_cr.Add(crs.ElementAt(i), cre.ElementAt(i));
    }
    for (int i = 0; i < elems.Count; i++)
        if (elems.ElementAt(i).LocalName.Equals("t"))
           if (isInsideAnyComment(dic_cr, elems.ElementAt(i)))
               for (int j = 0; j < dic_cr.Count; j++)
                   if (isInsideAComment(dic_cr.ElementAt(j), elems.ElementAt(i)))
                        String text = ((Text)elems.ElementAt(i)).InnerText;
    
    
    public bool isInsideAnyComment(IDictionary<CommentRangeStart, CommentRangeEnd> dic_cr, OpenXmlElement item)
        {
            foreach (var i in dic_cr)
                if (item.IsAfter(i.Key) && item.IsBefore(i.Value))
                    return true;
            return false;
        }
    
    public bool isInsideAComment(KeyValuePair<CommentRangeStart, CommentRangeEnd> dic_cr_elem, OpenXmlElement item)
        {
            if (item.IsAfter(dic_cr_elem.Key) && item.IsBefore(dic_cr_elem.Value))
                return true;
            return false;
        }