OpenXML中书签后插入文本 [英] Inserting text after a bookmark in openxml
问题描述
我要寻找一种方式来插入使用OPENXML在Word文档书签后,一些文本。到目前为止,我已经能够用定位书签以下内容:
I am looking for a way to insert some text after a bookmark in a word doc using openxml. So far, i have been able to locate the bookmark using the following:
var bookmarks = mainPart.Document.Descendants<BookmarkStart>().ToList();
var bookMarkToWriteAfter = bookmarks.FirstOrDefault(bm => bm.Name == insertAfterBoomark.Name);
这书签在Word文档是在doc两行选择。我有两个选择行权后插入一些文本。我曾尝试使用下面插入文字:
This bookmark in the word doc is a selection of two lines in the doc. I have to insert some text right after the two line selection. I have tried to insert text using the following:
var run = new Run();
run.Append(new Text("Hello World"));
bookMarkToWriteAfter .Parent.InsertAfterSelf(run);
mainPart.Document.Save();
然而,这无法产生预期的结果。有谁知道使用OPENXML在Word文档书签之后插入文本的正确方法是什么?
This however does not produce the desired result. Does anyone know of the correct way to insert text right after a bookmark in a word doc using openxml?
推荐答案
使用
bookMarkToWriteAfter.Parent.InsertAfterSelf(run);
您正试图用XML直接,这并不总是可取的OpenXML的工作。
you are trying to work with XML directly which is not always advisable with OpenXML.
试试这个..
Body body = mainPart.Document.GetFirstChild<Body>();
var paras = body.Elements<Paragraph>();
//Iterate through the paragraphs to find the bookmarks inside
foreach (var para in paras)
{
var bookMarkStarts = para.Elements<BookmarkStart>();
var bookMarkEnds = para.Elements<BookmarkEnd>();
foreach (BookmarkStart bookMarkStart in bookMarkStarts)
{
if (bookMarkStart.Name == bookmarkName)
{
//Get the id of the bookmark start to find the bookmark end
var id = bookMarkStart.Id.Value;
var bookmarkEnd = bookMarkEnds.Where(i => i.Id.Value == id).First();
var runElement = new Run(new Text("Hello World!!!"));
para.InsertAfter(runElement, bookmarkEnd);
}
}
}
mainPart.Document.Save();
这篇关于OpenXML中书签后插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!