OpenXml-遍历段落的运行并查找运行中是否具有斜体或粗体文本 [英] OpenXml - iterate through a paragraph's runs and find if a run has italic or bold text
本文介绍了OpenXml-遍历段落的运行并查找运行中是否具有斜体或粗体文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试遍历段落运行,查找运行是否带有斜体/粗体文本,然后将该文本替换为其他内容.
I am trying to iterate through paragraph runs, find if a run has italized/bold text and replace that text with something else.
就性能而言,哪一种是最好的方法.
Which is the best method in terms of performance.
推荐答案
如果您仅对嵌入式标记感兴趣,以下代码可以提供帮助.只需将Convert()方法更改为所需的任何内容即可.
If you are interested only in inline tags, the following code can help. Just change the Convert() method to whatever you want.
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class Program
{
static void Main(string[] args)
{
using (var doc = WordprocessingDocument.Open(@"c:\doc1.docx", true))
{
foreach (var paragraph in doc.MainDocumentPart.RootElement.Descendants<Paragraph>())
{
foreach (var run in paragraph.Elements<Run>())
{
if (run.RunProperties != null &&
(run.RunProperties.Bold != null && (run.RunProperties.Bold.Val == null || run.RunProperties.Bold.Val) ||
run.RunProperties.Italic != null && (run.RunProperties.Italic.Val == null || run.RunProperties.Italic.Val)))
Process(run);
}
}
}
}
static void Process(Run run)
{
string text = run.Elements<Text>().Aggregate("", (s, t) => s + t.Text);
run.RemoveAllChildren<Text>();
run.AppendChild(new Text(Convert(text)));
}
static string Convert(string text)
{
return text.ToUpper();
}
}
这篇关于OpenXml-遍历段落的运行并查找运行中是否具有斜体或粗体文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文