Compartir a través de


How to: Remove a Document Part from an Office Open XML Package by Using the Open XML API

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The Office Open XML Package specification defines a set of XML files that contain the content and define the relationships for all of the document parts stored in a single package. These packages combine the parts that comprise the document files for Microsoft® Office Excel® 2007, Microsoft Office PowerPoint® 2007, and Microsoft Office Word 2007. The Open XML Application Programming Interface (API) allows you to create packages and manipulate the files that comprise the packages. This topic walks through the code and steps to remove a document part (file) from an Open XML Formatted Package in Office Word 2007, although the steps are the same for each of the three 2007 Microsoft Office system programs that support the Office Open XML Format.

NoteNote

The code samples in this topic are in Microsoft Visual Basic® .NET and Microsoft Visual C#®. You can use them in an add-in created in Microsoft Visual Studio® 2008. For more information about how to create an add-in in Visual Studio 2008, see Getting Started with the Open XML Format SDK 1.0.

Removing a Document Part from a Package

In the following code, you remove a document part from a package:

' How to remove a document part from a package.
Public Shared Sub RemovePart(ByVal document As String)
   Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, true)
   Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart
   If (Not (mainPart.DocumentSettingsPart) Is Nothing) Then
      mainPart.DeletePart(mainPart.DocumentSettingsPart)
   End If
End Sub
// How to remove a document part from a package.
public static void RemovePart(string document)
{
  using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
  {
     MainDocumentPart mainPart = wordDoc.MainDocumentPart;
     if (mainPart.DocumentSettingsPart != null)
     {
        mainPart.DeletePart(mainPart.DocumentSettingsPart);
     }
  }
}

To remove a part from a package

  1. First, pass in parameters representing the path to and name of the source Word 2007 document.

  2. Then, open the document as a WordprocessingDocument object.

  3. Next, create a reference to the DocumentSettingsPart part. If that part exists, then the part is deleted from the package.

    In this instance, the settings.xml part is removed from the package.