In Aspose.Words, use the class
Bookmark to work with a single bookmark ant the BookmarkCollection class to work with a collection of bookmark objects.
The following code example shows how to get and set bookmark text in a document:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
|
|
Document doc = new Document(MyDir + "Bookmark.docx");
|
|
|
|
// Rename a bookmark and edit its text.
|
|
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
|
|
bookmark.Text = "This is a new bookmarked text.";
|
|
|
|
doc.Save(ArtifactsDir + "Bookmark text - Aspose.Words.docx"); |
You can also do the same using the Open XML SDK. At the same time, note that it looks somewhat more complicated and more cumbersome.
The following code example shows how to get and set bookmark text in a document:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
|
|
File.Copy(MyDir + "Bookmark.docx", ArtifactsDir + "Bookmark text - OpenXML.docx", true);
|
|
|
|
// Open the original Wordprocessing document.
|
|
using WordprocessingDocument doc = WordprocessingDocument.Open(ArtifactsDir + "Bookmark text - OpenXML.docx", false);
|
|
|
|
MainDocumentPart mainPart = doc.MainDocumentPart;
|
|
|
|
// Find the bookmark in the new document
|
|
BookmarkStart bookmark = mainPart.Document.Descendants<BookmarkStart>()
|
|
.FirstOrDefault(b => b.Name == "MyBookmark");
|
|
|
|
// Get the parent element of the bookmark
|
|
OpenXmlElement parentElement = bookmark.Parent;
|
|
|
|
// Create a new run with the new text
|
|
Run newRun = new Run(new Text("This is a new bookmarked text."));
|
|
|
|
// Replace the bookmark with the new text
|
|
parentElement.RemoveAllChildren(); // Remove existing content
|
|
parentElement.Append(newRun); // Add new text
|
|
|
|
// Save changes to the new document
|
|
mainPart.Document.Save(); |