OpenXml - iterate through a paragraph's runs and find if a run has italic or bold text

牧云@^-^@ 提交于 2019-12-07 13:23:27

问题


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.


回答1:


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



回答2:


It depends on whether you want to count inherited bold/italic from styles or are just interested in inline bold/italic tags.



来源:https://stackoverflow.com/questions/10620115/openxml-iterate-through-a-paragraphs-runs-and-find-if-a-run-has-italic-or-bol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!