OpenXml - 遍历段落的运行并查找运行是否包含斜体或粗体文本

etr*_*etr 3 openxml visual-studio-power-tools

我试图遍历段落运行,查找运行是否有italized /粗体文本并用其他东西替换该文本.

就性能而言,哪种方法最好.

小智 5

如果您只对内联标记感兴趣,以下代码可以提供帮助.只需将Convert()方法更改为您想要的任何内容.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)