OpenXml - iterate through a paragraph space and search if the run has italics or bold text

I am trying to iterate through paragraph runs, find if the selected text is selected in the run, and replace that text with something else.

What is the best method in terms of performance.

+3
source share
2 answers

If you are only interested in inline tags, the following code may 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();
    }
}
+4
source

It depends on whether you want to consider styles inherited in bold / italics, or just interested in the built-in bold / italics.

0
source

All Articles