Printing the Parts of an Open XML Document

[Blog Map]  [Table of Contents]  [Next Topic]

An easy way to see the XML in the parts of a WordprocessingML document is to create one in your word processor, save it, and then run the following program that prints the XML to the console.  You can also rename the file, adding a ".zip" to the end, and then extract the parts.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCThis example uses classes found in the WindowsBase and the DocumentFormat.OpenXml assembly.  The namespace for the classes is DocumentFormat.OpenXml.Packaging.

The following code is attached to this page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;

class Program
{
public static XDocument LoadXDocument(OpenXmlPart part)
{
XDocument xdoc;
using (StreamReader streamReader = new StreamReader(part.GetStream()))
xdoc = XDocument.Load(XmlReader.Create(streamReader));
return xdoc;
}

static void Main(string[] args)
{
const string filename = "Test.docx";

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename, true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
XDocument xDoc = LoadXDocument(mainPart);
Console.WriteLine(xDoc);
}
}
}

[Blog Map]  [Table of Contents]  [Next Topic]

PrintingThePartsOfAnOpenXmlDocument.cs