使用 OpenXML 将多行文本插入富文本内容控件

Insert multiple lines of text into a Rich Text content control with OpenXML

我很难让内容控件遵循多行格式。它似乎从字面上解释了我给它的一切。我是 OpenXML 的新手,我觉得我一定错过了一些简单的东西。

我正在使用此函数转换我的多行字符串。

    private static void parseTextForOpenXML(Run run, string text)
    {
        string[] newLineArray = { Environment.NewLine, "<br/>", "<br />", "\r\n" };
        string[] textArray = text.Split(newLineArray, StringSplitOptions.None);

        bool first = true;

        foreach (string line in textArray)
        {
            if (!first)
            {
                run.Append(new Break());
            }

            first = false;

            Text txt = new Text { Text = line };
            run.Append(txt);
        }
    }

我用这个插入到控件中

    public static WordprocessingDocument InsertText(this WordprocessingDocument doc, string contentControlTag, string text)
    {
        SdtElement element = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>().Val == contentControlTag);

        if (element == null)
            throw new ArgumentException("ContentControlTag " + contentControlTag + " doesn't exist.");

        element.Descendants<Text>().First().Text = text;
        element.Descendants<Text>().Skip(1).ToList().ForEach(t => t.Remove());

        return doc;
    }

我用类似...的方式称呼它

doc.InsertText("Primary", primaryRun.InnerText);

尽管我也尝试过 InnerXML 和 OuterXML。结果看起来像

示例收件人示例公司示例地址New York, NY 12345 或

<w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:t>Example Attn</w:t><w:br /><w:t>Example Company</w:t><w:br /><w:t>Example Address</w:t><w:br /><w:t>New York, NY 12345</w:t></w:r>

该方法适用于简单的文本插入。就在我需要它来解释 XML 时,它对我不起作用。

我觉得我一定非常接近得到我需要的东西,但我的摆弄让我无处可去。有什么想法吗?谢谢。

我相信我尝试这样做的方式注定要失败。设置元素的 Text 属性总是会被解释为要显示的文本。我最终不得不采取稍微不同的策略。我创建了一个新的插入方法。

    public static WordprocessingDocument InsertText(this WordprocessingDocument doc, string contentControlTag, Paragraph paragraph)
    {
        SdtElement element = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>().Val == contentControlTag);

        if (element == null)
            throw new ArgumentException("ContentControlTag " + contentControlTag + " doesn't exist.");

        OpenXmlElement cc = element.Descendants<Text>().First().Parent;
        cc.RemoveAllChildren();
        cc.Append(paragraph);

        return doc;
    }

同样开始,通过搜索它的Tag得到Content Control。但后来我得到它的父元素,删除那里的内容控件元素,然后用段落元素替换它们。

这与我预想的不完全一样,但它似乎符合我的需要。