[英]OpenXml - Find the index of the first Run element in a paragraph
我試圖在段落上使用文字處理InsertAt
方法,但是當我使用此方法時,段落樣式始終設置為null。 我發現我正在使用的索引為0,代表ParagraphProperties,而Run的索引為1。但是,當未設置段落屬性時,Paragraph唯一的子元素是Run
是否有一致的方法來查找“運行”所在的索引? 還是總是0或1?
上下文代碼段
var run = new W.Run() { RunProperties = new W.RunProperties() { NoProof = new W.NoProof() } };
run.AppendChild(dr);
para.InsertAt(run, 0);
顯然,我可以執行Math.Min(1, para.Count - 1)
但是我不確定是否可以將其他任何元素添加到段落中,並且Run元素最終成為中間元素
一個段落可以包含多個運行。 例如:
<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:r>
<w:t>Some text</w:t>
</w:r>
<w:r>
<w:rPr>
<w:noProof />
</w:rPr>
<w:t>Other text</w:t>
</w:r>
<w:r>
<w:t>Last text in paragraph</w:t>
</w:r>
</w:p>
因此,問題的答案實際上取決於您要完成的工作。 根據您的答案,您似乎想在Paragraph
已經存在的Run
之前添加新的Run
。
Paragraph
類具有一些有用的方法,例如InsertBefore
, InsertAfter
等,fx:
Paragraph p = ...
Run r = new Run(...);
p.InsertBefore(r, p.GetFirstChild<Run>());
這將使該段成為第一個Run
-假設該段中已經存在一個Run
。
您可以嘗試使用OpenXML生產率工具“查找”一些示例Word文檔。
我到目前為止已經完成了很長的路要走,如果有一個更干凈的解決方案,我將不勝枚舉。
int index = 0;
for (int i = 0; i < para.Count(); i++)
{
if (para.ElementAt(i) is W.Run)
{
index = i;
break;
}
}
para.InsertAt(run, index);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.