如何从文档中删除书签?

时间:2015-01-29 17:16:39

标签: openxml openxml-sdk

由于OOXML文档似乎没有遵循正确的XML规则,因此书签包含BookmarkStartBookmarkEnd和中间任意数量的元素;不是一个层次结构,而是一个必须以正确的顺序遍历的单个元素流:

<w:bookmarkStart w:id="4" w:name="Author"/>
    <w:r w:rsidR="009878B3"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>&lt;</w:t></w:r>
    <w:r w:rsidR="005E0909"><w:rPr><w:sz w:val="28"/></w:rPr><w:t xml:space="preserve"> </w:t></w:r>
    <w:r w:rsidR="009878B3"><w:rPr><w:sz w:val="28"/></w:rPr><w:t>Author&gt;</w:t></w:r>
<w:bookmarkEnd w:id="4"/>

我已在相关问题中遇到此问题:https://stackoverflow.com/questions/28219201/how-to-get-the-text-of-a-bookmark-as-a-single-string

但是这个问题是,如何在不破坏任何内容的情况下完全从文档中删除书签?我是否必须从BookmarkStart迭代兄弟姐妹,直到我到达BookmarkEnd?是否有一些有用的API方法可以弥补无法正确使用XML的情况,从而可以删除一个Bookmark节点?!

1 个答案:

答案 0 :(得分:0)

您可以通过API删除BookmarkStart,它会为您删除相应的BookmarkEnd并保留所有内容。在C#这样的事情应该有效:

public static void RemoveBookmark(string filename, string bookmarkName)
{
    using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filename, true))
    {
        Body body = wordDocument.MainDocumentPart.Document.Body;

        //find a matching BookmarkStart based on name
        BookmarkStart start = body.Descendants<BookmarkStart>().FirstOrDefault(b => b.Name == bookmarkName);

        if (start == null)
        {
            throw new Exception(string.Format("Bookmark {0} not found", bookmarkName));
        }

        //this is clever enough to remove the BookmarkStart and BookmarkEnd
        start.Remove();

        wordDocument.MainDocumentPart.Document.Save();
    }
}
相关问题