使用WordProcessingDocument时如何删除XMLSchemaReference?

时间:2016-03-01 14:43:39

标签: c# ms-word openxml wordprocessingml

我想从Word文档中删除XMLSchemaReference。运行VBA代码时,这很简单:

ActiveDocument.XMLSchemaReferences("ActionsPane3").Delete

在VSTO中使用ThisDocument类时,使用C#:

也很简单
Globals.ThisDocument.XMLSchemaReferences["ActionsPane3"].Delete();

但是,当使用WordProcessingDocument实例(在普通的Windows应用程序中)时,我不知道如何执行相同的操作。知道如何编写C#代码吗?

1 个答案:

答案 0 :(得分:1)

对于这样的问题,您可以做的最好的事情是下载Open XML SDK productivity tool并比较您在进行更改之前和之后所做的文档。当我使用VSTO添加动作窗格并在工具中探索包时,我注意到了这一点:

enter image description here

然后我使用您提供的代码删除动作窗格:

Globals.ThisDocument.XMLSchemaReferences["ActionsPane3"].Delete();
this.Save();

如果我们现在查看工具中的包,我们会有以下内容(请注意真棒写作):

enter image description here

现在我们已经确定了需要删除的内容,我们可以开始使用open xml sdk(using DocumentFormat.OpenXml.Packaging打开文件,using DocumentFormat.OpenXml.Wordprocessing进行修改)。在工具中保持文档打开以便能够使用树结构来构建代码总是很方便的。首先,我编写代码来打开并保存文档:

byte[] byteArray = File.ReadAllBytes(@"C:\WorkSpace\test\WordTest.docx");

using (var stream = new MemoryStream())
{
   stream.Write(byteArray, 0, byteArray.Length);
   using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
   {
       //Logic here
   }

   using (FileStream fs = new FileStream(@"C:\WorkSpace\test\WordTest_modified.docx", 
          FileMode.Create))
   {
      stream.WriteTo(fs);
   }
}

要删除AttachedSchema,您需要以下代码:

doc.MainDocumentPart.DocumentSettingsPart
                    .Settings
                    .GetFirstChild<AttachedSchema>()
                    .Remove();

如您所见,使用您旁边的树结构编写此内容非常方便。要删除SchemaReference,您需要以下代码:

doc.MainDocumentPart.CustomXmlParts.First()
                    .CustomXmlPropertiesPart
                    .DataStoreItem
                    .SchemaReferences
                    .FirstChild
                    .Remove();

然后就去了,就像你在VSTO应用程序中删除它一样。

修改:如果我执行以下行删除所有/docProps/custom.xml操作窗格已消失:

doc.CustomFilePropertiesPart.Properties.RemoveAllChildren();

我无法真正测试这是否是您的预期行为,因为我使用了测试文档(没有明显的大小变化),但现在看到我的操作窗格已经消失,它可能就是您正在寻找的(属性包含对本地vsto文件的引用)。我希望微软能够更好地记录这种东西。

相关问题