OpenXML中书签后插入文本 [英] Inserting text after a bookmark in openxml

查看:1275
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆