簡體   English   中英

如何使用 OpenXML Sdk 替換段落文本

[英]How to replace an Paragraph's text using OpenXML Sdk

我正在使用 .Net OpenXml SDK 2.0 解析一些 Openxml word 文檔。 作為處理的一部分,我需要用其他句子替換某些句子。 在迭代段落時,我知道何時找到了需要替換的內容,但我不知道如何替換它。

例如,假設我需要替換句子"a contract exclusively for construction work that is not building work." 將 html 片段添加到下面的 Sharepoint 可重用內容。

<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);

盡管我不太關心這個級別的格式,它似乎沒有任何格式,但外層 XML 似乎有額外的元素來打敗正則表達式。

..."16" /><w:lang w:val="en-AU" /></w:rPr><w:t>a</w:t></w:r><w:proofErr w:type="gramEnd" /> <w:rw: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 段落中的文本。 即使以丟失一些格式為代價。

自己修好了。 關鍵是刪除所有運行並在當前段落中創建新運行

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

所有段落內部都有一個 text 元素,因此您只需找到 text 元素並更新其文本,例如:

var text = part.RootElement.Descendants<Text>().FirstOrDefault(e=>e.Text == "a contract exclusively for construction work that is not building work.");
if(text != null)
{
    text.Text = "New text here";
}
mainPart.Document.Save();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM