我正在使用 .Net OpenXml SDK 2.0 解析一些 Openxml Word 文档。作为处理的一部分,我需要用其他句子替换某些句子。在遍历段落时,我知道何时找到需要替换的内容,但我对如何替换它感到困惑。
例如,假设我需要"a contract exclusively for construction work that is not building work."
用 html 片段将句子替换为下面的 Sharepoint Reusable 内容。
<span class="ms-rtestate-read ms-reusableTextView" contentEditable="false" id="__publishingReusableFragment" fragmentid="/Sites/Sandbox/ReusableContent/132_.000" >a contract exclusively for construction work that is not building work.</span>
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<Paragraph>(modifiedParagraph, currentParagraph);
尽管我不太关心这个级别的格式并且它似乎没有任何格式,但 outerXML 似乎有额外的元素破坏了正则表达式。
..."16" /><w:lang w:val="en-AU" /></w:rPr><w:t>a</w:t></w:r><w:proofErr w:type="gramEnd" /> <w:r w:rsidRPr="00C73B58"><w:rPr><w:sz w:val="16" /><w:szCs w:val="16" /><w:lang w:val="en-AU" /></w:rPr><w:t xml:space="preserve"> contract exclusively for construction work that is not building work.</w:t></w:r></w:p>
所以总而言之,我将如何用其他文本替换 OpenXml 段落中的文本。即使以丢失一些格式为代价。