OpenXML替换所有文档中的文本 [英] OpenXML replace text in all document

查看:298
本文介绍了OpenXML替换所有文档中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有一段代码.我想用"NewText"替换文本"Text1",这是可行的.但是,当我将文本"Text1"放置在表中后,该表中的"Text1"不再起作用.

I have the piece of code below. I'd like replace the text "Text1" by "NewText", that's work. But when I place the text "Text1" in a table that's not work anymore for the "Text1" inside the table.

我想在所有文档中进行替换.

I'd like make this replacement in the all document.

using (WordprocessingDocument doc = WordprocessingDocument.Open(String.Format("c:\\temp\\filename.docx"), true))
{
    var body = doc.MainDocumentPart.Document.Body;

    foreach (var para in body.Elements<Paragraph>())
    {
        foreach (var run in para.Elements<Run>())
        {
            foreach (var text in run.Elements<Text>())
            {
                if (text.Text.Contains("##Text1##"))
                    text.Text = text.Text.Replace("##Text1##", "NewText");
            }
        }
    }
}

推荐答案

您的代码不起作用,因为表元素(w:tbl)不包含在其中 段落元素(w:p).有关更多信息,请参见下面的 MSDN 文章.

Your code does not work because the table element (w:tbl) is not contained in a paragraph element (w:p). See the following MSDN article for more information.

Text类(序列化为w:t)通常表示文本中Run元素内的文字文本. Word文档.因此,您只需搜索所有w:t元素(Text类)并替换您的 标签,如果文本元素(w:t)包含您的标签:

The Text class (serialized as w:t) usually represents literal text within a Run element in a word document. So you could simply search for all w:t elements (Text class) and replace your tag if the text element (w:t) contains your tag:

using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true))
{
  var body = doc.MainDocumentPart.Document.Body;

  foreach (var text in body.Descendants<Text>())
  {
    if (text.Text.Contains("##Text1##"))
    {
      text.Text = text.Text.Replace("##Text1##", "NewText");
    }
  }
}

这篇关于OpenXML替换所有文档中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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