2017-02-27 124 views
0

我试图在段落上使用字处理InsertAt方法,但是当我使用此方法时,我的段落样式始终设置为null。我发现我使用的索引是0,是ParagraphProperties,Run是索引1.但是,当没有设置段落属性时,唯一的子元素段落是运行OpenXml - 在段落中查找第一个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),但我不能确定是否有任何其他的元素可以被添加到该段和运行要素最终被中间元素

回答

1

段落可以包含多个运行。例如:

<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

Paragraph类有一些方法是有用的喜欢InsertBeforeInsertAfter等,FX:

Paragraph p = ... 
Run r = new Run(...); 
p.InsertBefore(r, p.GetFirstChild<Run>()); 

这将使中的R段落中第一个Run - 假设已经存在的段落Run

您可以尝试使用OpenXML Productivity Tool'查看'一些示例文档。

+0

是的,我意识到可能有多个运行,我正在寻找第一个...更新问题标题,以反映:) 那么'para.InsertAt(run,indexOfFirstRun)'和'para .InsertBefore(run,para.GetFirstChild ())'? InsertAt方法似乎在索引提供之前插入(或者将其他所有内容向下移动,并将其插入到该索引处) – p3tch

+0

我仍然不确定为什么在ParagraphProperties索引处的InsertAt空值属性,但工作正常你插入一个运行的索引 – p3tch

0

我已经做到了“长”的方式,现在,如果有一个清洁的解决方案我所有的耳朵...

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