OpenXml - 查找段落中第一个 运行 元素的索引
OpenXml - Find the index of the first Run element in a paragraph
我正在尝试对段落使用文字处理 InsertAt
方法,但是当我使用此方法时,我的段落样式始终设置为 null。我发现我使用的索引 0 用于 ParagraphProperties,运行 位于索引 1。但是,当没有设置段落属性时,Paragraph 唯一的子元素是 运行
是否有一致的方法来查找 运行 所在的索引?还是总是 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)
的事情,但我不确定是否可以将任何其他元素添加到该段落并且 运行 元素最终成为中间元素
我现在已经按照 'long' 的方式完成了,如果有更清洁的解决方案,我会洗耳恭听...
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);
一个段落可以包含多个运行。例如:
<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
class 有一些有用的方法,如 InsertBefore
、InsertAfter
等,fx:
Paragraph p = ...
Run r = new Run(...);
p.InsertBefore(r, p.GetFirstChild<Run>());
这将使 r 成为段落中的第一个 Run
- 假设段落中已经有一个 Run
。
您可以使用 OpenXML Productivity Tool 尝试 'looking inside' 一些示例 word 文档。
我正在尝试对段落使用文字处理 InsertAt
方法,但是当我使用此方法时,我的段落样式始终设置为 null。我发现我使用的索引 0 用于 ParagraphProperties,运行 位于索引 1。但是,当没有设置段落属性时,Paragraph 唯一的子元素是 运行
是否有一致的方法来查找 运行 所在的索引?还是总是 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)
的事情,但我不确定是否可以将任何其他元素添加到该段落并且 运行 元素最终成为中间元素
我现在已经按照 'long' 的方式完成了,如果有更清洁的解决方案,我会洗耳恭听...
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);
一个段落可以包含多个运行。例如:
<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
class 有一些有用的方法,如 InsertBefore
、InsertAfter
等,fx:
Paragraph p = ...
Run r = new Run(...);
p.InsertBefore(r, p.GetFirstChild<Run>());
这将使 r 成为段落中的第一个 Run
- 假设段落中已经有一个 Run
。
您可以使用 OpenXML Productivity Tool 尝试 'looking inside' 一些示例 word 文档。