none
Serializing OpenXML Parts Elements Storing in VARBINARY SQL 2005 RRS feed

  • Question

  • I am building a solution that allows users to pick and chose sections from a Word template, populate those sections with content from a database, and assemble the new data into a new .docx document

    So far, I have successful methodologies for locating content and transplanting that content into a new document.  I am using the OpenXML SDK 2.0 to locate content by Styles and Content Controls. I am able to create IEnumerable objects containing elements such as Paragraphs, SdtBlocks, Run, etc.

     

    I need to find an elegant way to serialize these element blocks so I can store them as whole blocks of type VARBINARY in a SQL 2005 database. Can someone please point me to a viable example for serializing these OpenXML parts/elements?


    Cory Mathewson
    Friday, January 7, 2011 5:32 PM

Answers

  • You use the .GetStream method.

    The following is an example of copying a theme part from two documents but you can use the idea to store and retrieve your parts/elements from a database. One way would be to convert the stream into a byte array and store it in SQL Server.

    http://msdn.microsoft.com/en-us/library/bb463673.aspx

    // To copy contents of one package part.
    public static void CopyThemeContent(string fromDocument1, string toDocument2)
    {
      using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(fromDocument1, false))
      using (WordprocessingDocument wordDoc2 = WordprocessingDocument.Open(toDocument2, true))
      {
       ThemePart themePart1 = wordDoc1.MainDocumentPart.ThemePart;
       ThemePart themePart2 = wordDoc2.MainDocumentPart.ThemePart;
    
        using (StreamReader streamReader = new StreamReader(themePart1.GetStream()))
        using (StreamWriter streamWriter = new StreamWriter(themePart2.GetStream(FileMode.Create))) 
       {
         streamWriter.Write( streamReader.ReadToEnd() );
       }
      }
    }
    


    ClosedXML - The easy way to OpenXML
    • Marked as answer by Bessie Zhao Friday, January 14, 2011 10:48 AM
    Sunday, January 9, 2011 6:54 PM