如何使用OpenXML Sdk替换Paragraph的文本

我正在使用.Net OpenXml SDK 2.0解析一些Openxml word文档。 作为处理的一部分,我需要用其他句子替换某些句子。 在迭代段落时,我知道当我找到需要替换的东西时,但我很难过如何替换它。

例如,假设我需要替换"a contract exclusively for construction work that is not building work."这句话"a contract exclusively for construction work that is not building work." 使用html片段到下面的Sharepoint可重用内容。

a contract exclusively for construction work that is not building work.

PS:我使用xslt得到了docx到Html的转换,所以在这个阶段这不是问题

Paragraph节点的InnerText属性为我提供了正确的文本,但内部文本属性本身不可设置。 所以Regex.Match(currentParagraph.InnerText, currentString).Success返回true并告诉我当前段落包含我想要的文本。

正如我所说,InnerText本身不可设置,所以我尝试使用outerxml创建一个新的段落如下。

 string modifiedOuterxml = Regex.Replace(currentParagraph.OuterXml, currentString, reusableContentString); OpenXmlElement parent = currentParagraph.Parent; Paragraph modifiedParagraph = new Paragraph(modifiedOuterxml); parent.ReplaceChild(modifiedParagraph, currentParagraph); 

尽管我并不太关心这个级别的格式化并且它似乎没有任何格式,但是outerXML似乎有额外的元素可以打败正则表达式。

..."16" />a contract exclusively for construction work that is not building work.

总而言之,我如何将OpenXml段落中的文本替换为其他文本。 即使以牺牲一些格式为代价。

我自己修好了。 关键是删除所有运行并在当前段落中创建新运行

 string modifiedString = Regex.Replace(currentParagraph.InnerText, currentString, reusableContentString); currentParagraph.RemoveAllChildren(); currentParagraph.AppendChild(new Run(new Text(modifiedString)));