Partager via


Retrieving the Default Style Name of an Open XML WordprocessingML Document

Whenever I write some Open XML SDK code that processes paragraphs based on style name, I need to retrieve the default style name for a document.  It is pretty easy to do, but it always takes a small bit of time to remember / lookup the element and attribute names.  Posting this code here so that I can save time next time I need to do this...

This code uses the utility types (preatomized XName objects and the GetXDocument extension method) in PtOpenXmlUtil.cs, which you can find in HtmlConverter.zip under the downloads section at CodePlex.com/PowerTools.

This is one in a series of posts on transforming Open XML WordprocessingML to XHtml.  You can find the complete list of posts here.

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

Blog TOC

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

class Program
{
static void Main(string[] args)
{
byte[] byteArray = File.ReadAllBytes("Test.docx");
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Open(memoryStream, true))
{
string defaultParagraphStyleId = wordDoc
.MainDocumentPart
.StyleDefinitionsPart
.GetXDocument()
.Root
.Elements(W.style)
.Where(e => (string)e.Attribute(W.type) == "paragraph" &&
(string)e.Attribute(W._default) == "1")
.Select(s => (string)s.Attribute(W.styleId))
.FirstOrDefault();
Console.WriteLine(defaultParagraphStyleId);
}
}
}
}