Exemple #1
0
        /// <summary>
        /// 删除书签处的内容
        /// </summary>
        /// <param name="doc">Word文档对象</param>
        /// <param name="bookmarkName">书签名</param>
        public BookmarkStart RemoveBookmarkContent(WordprocessingDocument doc, string bookmarkName)
        {
            BookmarkStart bookmarkStart = FindBookmarkStart(doc, bookmarkName);
            BookmarkEnd   bookmarkEnd   = FindBookmarkEnd(doc, bookmarkStart.Id);

            while (true)
            {
                // NextSibling()获取紧跟当前 OpenXmlElement 元素的 OpenXmlElement 元素。 如果没有下一个 OpenXmlElement 元素,则返回 null
                var run = bookmarkStart.NextSibling();
                if (run == null)
                {
                    break;
                }

                if (run is BookmarkEnd end && end == bookmarkEnd)
                {
                    break;
                }

                run.Remove();
            }

            return(bookmarkStart);
        }
        private void DeleteBookmarkContent(BookmarkStart bookmarkStart)
        {
            var itemsToDelete = new List<OpenXmlElement>();
            var element = bookmarkStart.NextSibling();
            while (element != null && !(element is BookmarkEnd && ((BookmarkEnd)element).Id.Value == bookmarkStart.Id.Value))
            {
                itemsToDelete.Add(element);
                element = element.NextSibling();
            }

            foreach (var item in itemsToDelete)
            {
                item.Remove();
            }
        }