无法使用自定义XML填充Word Content Control

时间:2015-08-17 12:30:12

标签: c# xml replace ms-word

我尝试编写一些代码,使用XML文件使用某些内容控件填充Word文件。为此,我使用以下代码:

string outPath = @"D:\template_created.docx";
string docPath = @"D:\template.docx";
string xmlPath = @"D:\template.xml";

File.Copy(docPath, outPath);

using (WordprocessingDocument doc = WordprocessingDocument.Open(outPath, true))
{
    MainDocumentPart mdp = doc.MainDocumentPart;
    if (mdp.CustomXmlParts != null)
    {
        mdp.DeleteParts<CustomXmlPart>(mdp.CustomXmlParts);
    }

    CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml);
    FileStream fs = null;

    try
    {
        fs = new FileStream(xmlPath, FileMode.Open);

        cxp.FeedData(fs);
        mdp.Document.Save();
    }
    finally
    {
        if (fs != null)
        {
            fs.Dispose();
        }
    }
}

这是我的XML文件:

<root>
    <firstname_1>Marc</firstname_1>
    <lastname_1>Swit</lastname_1>
    <firstname_2>Paul</firstname_2>
    <lastname_2>Gevaert</lastname_2>
</root>

当我运行应用程序时,它创建了自定义XML文件并将其附加到我的Word文件中。当我打开Word文件时,没有错误,但所有内容控件都没有填写

当我将template_created.docx重命名为template_created.zip,提取文件并浏览它们时,我发现我的XML文件已正确创建并且在customXML文件夹中包含正确的内容。

有人有意帮助我吗?

谢谢!

编辑2015年8月17日:我在下面的答案中的第一个解决方案

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。实际上,首先我需要创建一个XML文件,其中包含与我的Contents Control相对应的所有元素,并在Word Content Control Toolkit中使用此文件后将XML附加到我的Word文件

之后,当我运行我的应用程序时,将填充招标工作和内容控制